All posts by Thiyagu

How to use Vim editor in PowerShell

If you are familiar with Linux or come from a Unix background, you probably know about Vim. For those of us that started and stay mostly in the realm of Windows however; I Let we exposed to vim editor in PowerShell, and see what it can do. Windows OS does not come with Vim as Unix-based systems do. 

Vim is a powerful, widely used text editor for Unix-based systems, including Linux and macOS. It is known for its speed, efficiency, and flexibility, making it a popular choice among programmers, system administrators, and other power users who need to edit text files on a regular basis. Vim is a command-line interface (CLI) application that can be used in a terminal window, and it provides a wide range of commands and keyboard shortcuts for navigating and editing text files.

Why we need this editor?

Did you run a script that read a text file and need to change something in config for debugging or found that the file had several wrong entries? A PowerShell text editor may come in handy in such situations. You wouldn’t need to fire up an external editor or not have permission to open the file directly. Instead, you can edit the file without leaving PowerShell. How cool is that?

You can also read : If you want to check if script is running in admin privileges,

How to use vim editor in PowerShell

To edit a text file using the Vim editor in PowerShell, follow below steps:

Install the Vim editor in PowerShell

STEP 1: Open PowerShell as an Administrator.

Open PowerShell by searching for “PowerShell” in the Start menu and selecting “Windows PowerShell” or “Windows PowerShell (x86)” in admin.

STEP 2: Install Vim editor in PowerShell using Chocolatey

In the PowerShell terminal, execute the following command to install the Vim editor.

choco install vim -y

Install the Vim in Powershell

STEP 3: To verify the Vim version, run the following command

vim –version

Editing and Saving a File using Vim

For this demo, I already having the txt file (in c:\mytestfile) where i am going to edit & save my changes. By following the above steps, now that you have Vim installed, it’s time to get you to learn to edit a file. Before you go any further, you should know that there are different modes in Vim. Each mode behaves differently and affects which actions you can do inside the editor.

The three commonly-used modes are:

  • Normal – The default mode as soon as you open Vim. This mode allows you to navigate the text file but not add new texts.
  • Insert – This mode is where Vim allows you to edit the file. To enter this mode, press i (case insensitive) on the keyboard. To exit and go back to the normal mode, press ESC.
  • Command – In this mode, Vim lets you invoke commands such as save the file, quit Vim, or view the help document, among others.

STEP 4: Open a file using Vim Command

To open the file, run the vim command followed by the filename to open. The command below opens the mytestfile.txt file in the PowerShell console and its ready for view and edit . 

vim “c:\thiyagu disck\mytestfile.txt

STEP 5: Enable the Insert Mode for the file

Next, enter the insert mode by pressing “i”. As you enter the insert mode, the text — INSERT — appears at the bottom of the editor, as shown in the following image. Now that you are in insert mode edit the file as you wish. The arrow keys will let you move the cursor inside the editor.

For this example I added new line as highlighted in the yellow arrow.

STEP 6: Append changes & Save

After making the necessary changes to the text file, press Esc to return to normal mode and Type the command :wq and press Enter to save and close the file. The command w saves the files while q exits Vim.

Output:

 

How to create new DNS in Azure Private DNS using PowerShell

You have a more number of options when it comes to resolving names using DNS. Microsoft Azure DNS is one of such option. In this post, we will discuss How to create new DNS in the Azure Private DNS using PowerShell

To manage Azure DNS, you can configure it through Azure Portal UI or command-line tools like the Azure CLI or PowerShell. Often admins need to manage DNS at scale or automate the management of various objects. A great way to do that isn’t via a graphical method like the Azure Portal but with a scripting tool like PowerShell (as we can automate).

Azure DNS is a managed DNS solution. We can use it for public DNS records (use the URL for access public) as well as for private DNS records. Using Azure private DNS, we can resolve DNS names in a virtual network. There are many benefits to using Azure private DNS.

  • No additional servers – We do not need to maintain additional servers to run the DNS solution. It is a fully managed service.
  • Automatic Record Update – Similar to Active Directory DNS, we can configure Azure DNS to register/update/delete hostname records for virtual machines automatically.
  • Support common DNS record types – It supports common DNS record types such as A, AAAA, MX, NS, SRV, and TXT.
  • DNS resolution between virtual networks – Azure Private DNS zones can be shared between virtual networks.

 As we had to set many URLs so we thought to have automation to create through Azure DevOps Pipeline.

using New-AzPrivateDnsRecordSet cmdlet we can able to create a new DNS record in the Azure DNS zone and Get-AzPrivateDnsRecordSet will use to list out all the DNS records which were created. The Set-AzPrivateDnsRecordSet cmdlet updates a record set in the Azure Private DNS service from a local RecordSet object. You can pass a RecordSet object as a parameter or by using the pipeline operator

Prequistion for making automation for creating a record set in a Private DNS zone.

  • -Name : The name of the records in this record set (relative to the name of the zone and without a terminating dot).
  • -RecordType : The type of Private DNS records in this record set (values may be A, AAAA, CNAME, MX, PTR, SOA, SRV, TXT)
  • -ZoneName : The zone in which to create the record set (without a terminating dot). In my case, all the domains need to be like .cloud.dotnethelpers.com. for example,
    preprod.cloud.dotnethelpers.com.
  • -ResourceGroupName : The resource group to which the zone belongs.
  • -Ttl : The TTL value of all the records in this record set.
  • -PrivateDnsRecords : The private DNS records that are part of this record set.
  • -Ipv4Address: The IPv4 address for the A record to add. For me this ip from the ingress, in your case it may be your server or anything.

Script: How to create new DNS

New-AzPrivateDnsRecordSet -Name pprd -RecordType A -ZoneName “cloud.dotnethelpers.com” -ResourceGroupName “rg-dgtl-network-pprd” -Ttl 3600 -PrivateDnsRecords (New-AzPrivateDnsRecordConfig -IPv4Address “10.55.161.23”)

Script: How to get DNS record details

Get-AzPrivateDnsRecordSet -ResourceGroupName ‘rg-dgtl-network-pprd’ -ZoneName ‘cloud.dotnethelpers.com’ -RecordType A

Script: How to detect DNS record

$RecordSet = Get-AzPrivateDnsRecordSet -Name “cd-ppr” -ResourceGroupName “rg-dgtl-network-pprd” -ZoneName “cloud.dotnethelpers.com” -RecordType A
Remove-AzPrivateDnsRecordSet -RecordSet $RecordSet

Output: 

The final URL will be pprd.cloud.dotnethelpers.com

Points to Remember:

Before running the above script ensure you have installed the required module in PowerShell to connect to the Azure portal to access the resources (connect using the Connect-AzAccount cmdlet). I hope you have a basic idea about How to create  new DNS in the Azure Private DNS using PowerShell, if any queries please comment so I can able to answer ASAP.

Trigger Azure DevOps pipeline automatically using PowerShell

In many situations, we need to trigger pipelines automatically or from another pipeline (it may be another build pipeline or release pipeline). In my project, I had the same situation where I need to trigger the build from the release pipeline, in my case, the build (CI) pipeline is written in the YAML, and the release (CD) pipeline is configured in the classic editor.

How we can trigger pipelines automatically?

Trigger pipelines automatically can be achieved using Azure tasks or using PowerShell (can be done through the API using PowerShell). Using this, you can trigger a build or release pipeline from another pipeline within the same project or organization but also in another project or organization.

In this example, we will be going to discuss how we can achieve this through PowerShell using the API. in a future post, we can discuss how we can achieve using the task in Powershell.

Step: 1 Create the PAT token for Authorization

To get started, a Personal Access Token is required with the appropriate rights to execute pipelines. To generate a new Personal Access Token follow the link:

Step: 2 Enycrpt the PAT token

Always encrypt the pat token before using it in our script and kept the pat in Keyvalut. For this example, I used direct here for our example.

$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(“:$($token)”))

Step: 3 Define the API and assign it to variable

This was the latest API version 7.0 which I am going to use for Triggering the pipeline automatically using PowerShell Azure DevOps. As the name implies, we can able to get the {organization}/{project} name easily. if you are new to Azure DevOps, they will struggle to find the {pipelineId}. please find the below snapshot for reference, after clicking on the pipeline which you need to trigger, there you are able to find the build?definitionid which is called as pipelineId.

Syntax : https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=7.0

$url=”https://dev.azure.com/myOrganization/Myproject/_apis/pipelines/4/runs?api-version=7.0″

 

step: 4 Pass the parameter in the body of API.

This action in required as there are a lot of branches in my repo and the build needs to understand from which branch the build needs to be triggered so I am going to pass the branch name for the pipeline.

$JSON = @’
{
“self”: { “refName”:”develop”},
}
‘@

Step: 5 Invoke the API to trigger pipelines automatically

In this example, I am going to use the PowerShell task to execute the below script as shown in the below snapshot to Trigger the pipeline automatically.

 

$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = “Basic $token”} -Method Post -Body $JSON -ContentType application/json

Full Code

$token = '5dfdferedaztxopaqwxkzf7kk4xgfhn5x5akuvgn3tycwsehlfznq'
$url="https://dev.azure.com/myOrganization/Myproject/_apis/pipelines/4/runs?api-version=7.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))

$JSON = @'
{
"self": { "refName":"develop"},
}
'@

$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json

 

Azure KeyVault Set and Retrieve Secrets using Powershell

What is Key Vault?

Azure Key Vault is a cloud service that works as a secure secrets store. You can securely store keys, passwords, certificates, and other secrets.

In this example, I am going to create/fetch secrets in Azure key vault secrets using the PowerShell task in the Azure DevOps, so for this, you need to ensure your Agent (it may be self-hosted or default Agent) has access to the Azure Key vault.

Note: Az Module is required for performing the below operations.

STEP: 1 Connect to Azure using Connect-AzAccount

After executing the below cmdlet, you will get the pop for authentication, post successful authentication you will able to execute from the STEP 2

Connect-AzAccount

STEP: 2 Convert the Values to Secure String

Before pushing the secrets in the Azure key vault ensure you are Converts plain text to encrypted strings to secure.

$captcha_value = ConvertTo-SecureString ‘5KjciMedTTTTTJObOOpwysZPFDH-M-TOx1OIuDt6’ -AsPlainText -Force

STEP: 3 Set the Secrets using set-AzKeyVaultSecret

set-AzKeyVaultSecret -VaultName kv-dgtl-dev -Name ‘captcha-secret-key’ -SecretValue $captcha_value

STEP: 4 Get the Secrets using Get-AzKeyVaultSecret

$captcha-secret = Get-AzKeyVaultSecret -VaultName kv-dgtl-dev -Name ‘captcha-secret-key’

To get the value in plain text just use -AsPlainText at the end of the command as shown below

$captcha-secret = Get-AzKeyVaultSecret -VaultName kv-dgtl-dev -Name ‘captcha-secret-key’ -AsPlainText

Quickly extracting all links from a web page using the PowerShell

We are maintaining 500+ client websites in our environment. Some day before we received a request to get the list of links/Images used on each home page. We knew that it will be very tricky to get the list of links/URLs mapped in the 500+ pages and you are also aware that the annual work will not give 100% results.

So we decided to use Powershell Links in the Invoke-WebRequest method to reduce manual effort. In this post, we will discuss the same with a simple example using a single URL. For checking the multiple URLs, please refer to a similar article which helps to read from excel and loop it –

https://dotnet-helpers.com/powershell/powershell-script-for-website-availability-monitoring-with-excel-report-as-output

PowerShell’s Invoke-WebRequest is a powerful cmdlet that allows you to download, parse, and scrape web pages. The Invoke-WebRequest cmdlet is used to download files from the web via HTTP and HTTPS. However, this cmdlet enables you to do more than download files. You can use this cmdlet for analyzing the contents of web pages.

Example: Get the list of URLs

The below script will grab the innerText in addition to the corresponding links

(Invoke-WebRequest -Uri “https://dotnet-helpers.com/powershell”).Links | sort-object href -Unique | Format-List innerText, href

Example: Get the list of URLs This gets the list of links with grid view control

The grid view control lets you filter URLs with keyword search and you will copy the listings to the clipboard by using the Ctrl + C option.

(Invoke-WebRequest -Uri “www.lantus.com”).Links.Href | Sort-Object | Get-Unique | out-gridview

Example: Get the list of Image URLs

To fetch the list of image URLs from the page, you can run the below cmdlet

(Invoke-WebRequest -Uri “https://dotnet-helpers.com”).Images | Select-Object src

Run BAT File From PowerShell Script

To Run BAT File from PowerShell Script, you can run it manually from the PowerShell (or make the PowerShell execution in the windows scheduler run at a certain time). 

A batch file is a series of commands or a script in the Windows Operating System that executes a series of tasks on the local or remote machines and it has a. Bat extension. Although PowerShell and Batch are different languages, both can be integrated into each other and helps to call and execute each other.

This article will illustrate different ways to run a Batch file from a PowerShell script.

Step #1 Create a .bat file with commands

For time being, I only used the echo command in the bat file, you can write your logic command as required. For this example, I save the file as CallMe.bat.

echo Write something, it will be used in the command “echo”
pause

Step #2 Create a Powershell script file & call the .bat file

There are many approaches we can call the .bat file from PowerShell, which we can choose based on our purpose. This step will guide you on how to Add the Batch file to a PowerShell script to run automatically when the PowerShell script is being run.

Method: 1

One way of running a Batch file from the PowerShell script is using the Start-Process cmdlet. The Start-Process cmdlet allows you to run one or multiple processes on your computer from within PowerShell.
It’s designed to run a process asynchronously or to run an application/script elevated (with administrative privileges).

To run the Batch file, add the following line of code to the PowerShell script:

Filepath specifies the path of the Batch file.
NoNewWindow starts the process in the current window (add this at end of the script to mention not to open the cmd window).

Start-Process -FilePath ‘C:\blog\callme.bat’

To run the Batch file as administrator, add -verb run as in the above code. This command is useful when your .bat file contains commands which require administrator privileges to run on execution.

Start-Process -FilePath ‘C:\blog\callme.bat’ -Verbose Runas -NoNewWindow

Output

Method: 2

/c referred to Carries out My Command and then terminates

cmd.exe /c ‘C:\blog\callme.bat’

Method : 3

& C:\blog\callme.bat

How to Create Your First simple Jenkins Pipeline

In our first Jenkins tutorial for beginners, we focused on how to install and configure Jenkins. In this tutorial, How To Create Your First simple Jenkins Pipeline. We’ll keep it simple and avoid Maven or Git at this juncture. We’ll just create a Jenkins freestyle job that invokes the JDK’s runtime instance and prints out the version of the JRE that is currently running in the Jenkins machine (location of Jenkins installation).

STEP: 1 Login into Jenkins and go to Jenkins dashboard

To create a Jenkins freestyle job, log on to your Jenkins dashboard by visiting your Jenkins installation path. Usually, it will be hosted on localhost at http://localhost:8080 If you have installed Jenkins in another path, use the appropriate URL to access your dashboard as shown in the below Jenkins job creation example.

STEP: 2 Create New Item (New job/pipeline)

The first step to creating a Jenkins build job is to click the New Item link in the top left-hand corner of the admin console and enter the Item name & click Ok.

Note: If you are unable to see this icon, it means that you don’t have sufficient privileges. In the next window, type the name of the job such as the first job, select job type as freestyle job, and then click ok:

STEP 3: Configure the new job details

After clicking OK ( in STEP 3), the configuration page for the freestyle Jenkins job will appear as shown in the below snapshot. Notice there are a number of options to configure, including build triggers, source code management options, Jenkins build job steps, and post-build actions. As we mentioned in starting of the post, we are only going to create simple jobs without doing any build or deployment.

In the Jenkins build job, we will change the description to “My_First_JenkinsJob” and Under the “Source Code Management” section, for this example, we are not going to use any GIT URL to download the solution so you can select “None”

In this job/pipeline, we going the check the java version that was installed in our local/Jenkins machine. For this, in the “Build section” choose “Execute Windows batch command” from the drop-down and type the “java -version” in the window batch command section.

STEP 4: Save the job and click on the Build Now link.

Now your Jenkins Job is ready for checking the version of Java installed on the Jenkins machine.

STEP 5: Save the job, click on the Build icon & Check the status.

To run the created job, click on the job which you need to build. Once the new job is opened as shown in the below snapshot, click the “Build Now” to start the job execution. You can check the build status under the “Build History section” at the left bottom of the screen.

STEP 6: View the log for checking the output

In the window batch command, we placed the cmd to check the version of java.  So the same has been executed and you can able to see the output in the log file as shown in the below image.

Based on this simple example, I now hope you can able to Create Your First simple Jenkins Pipeline.

Install Jenkins on Windows – A Step-By-Step Guide

In this article, we will go through the steps to download and install Jenkins on Windows. Jenkins is a free and open-source automation software used for building, testing, and deploying code to achieve the end goal of Continuous Delivery and Continuous Integration. It provides faster and more efficient code deployment in multiple environments. Jenkins supports a wide range of plugins due to which it can deploy almost any kind of code to any environment.

What is Jenkins?

Jenkins is a self-contained, open source (DevOps tool) automation server which can be used to automate all sorts of tasks related to building, testing and delivering or deploying software. Jenkins can be installed through native system packages, Docker, or even run standalone by any machine with a Java Runtime Environment (JRE) installed.

Jenkins may be installed on either Windows/Unix/supported platforms, but we will focus only install Jenkins on a Windows machine in the article (the below steps explain the installation in the standalone machine).

STEP 1: Prerequisites

Before you proceed to install Jenkins in your windows/Unix system, there are some prerequisites for Jenkins to install Jenkins on your computer.

Hardware requirements:

  • Hardware requirements (Minimum): 256 MB of RAM, 1 GB of drive space (although 10 GB is a recommended minimum if running Jenkins as a Docker container)
  • Hardware configuration for a small team (Recommended) : 4 GB+ of RAM & 50 GB+ of drive space

Software Requirements:

  • You should have the latest Java software installed as a prerequisite. Since Jenkins runs on Java, you need either the latest version of Java Development Kit (JDK) or Java Runtime Environment (JRE).
  • You should have access to install Software on Windows Server.

You can refer to the prerequisites of Jenkins in Jenkins.io

STEP 2: Choose the type of Jenkins download 

Jenkins releases two types of versions based on the organization’s needs. The first one is the Long-term support release & Weekly release. First, you need to download the latest Jenkins software from Download Page. At the time of writing this article, Jenkins 2.289.3 is the latest version. This might be different for you.

Long-term support releases are available every 12 weeks. They are stable and are widely tested. This release is intended for end users.

Weekly releases are made available every week by fixing bugs in its earlier version. These releases are intended towards plugin developers.

For this article, we will use the LTS, and more of the steps will remain the same for the Weekly release.

STEP 3: Download the Jenkins tool

First you need to download the latest Jenkins software from Download Page. At the time of writing this article, Jenkins 2.346.2 is the latest version (May you will find the different version during your time).

STEP 4: Double-click on Downloaded setup

Go to download location from the local computer (unzip) and Double-click on jenkins.msi. You can also Jenkin using a WAR (Web application archive) but that is not recommended.

STEP 5: In the Jenkin Setup screen, click Next.

STEP 6: Choose the Installation location

Choose the location where you want to have the Jenkins instance installed (default location is C:\Program Files (x86)\Jenkins), then click on the Next button.

STEP 8: Service Logon

You need to provide user account credentials to run Jenkins as Independent Windows Service. These can be done using two different ways – run service as LocalSystem or run service as local or domain user. Usually, it is recommended to use a local or domain user to run the Jenkins Service but here we will run the service as LocalSystem. Then Click on Next.

STEP 9: Choose your port

By default Port 8080 will be used for running Jenkins Service but you can always change this port as per your need. Once port detail is given you can quickly check its availability by clicking on Test Port. If testing goes successful then Click on Next.

SETP 10: Select Java Home Directory

Since Jenkins requires Java Runtime Environment to run so here you need to provide the JRE path to proceed with the installation. 

STEP 11: Choose a Custom setup

If you want to install any other features during the installation process then you can select them from here and click on Next. You can also select and install other features post-Jenkins Installation.

STEP 12: Start the installation

If you see the below window then it means Jenkins is finally ready to install. You can now just click on Install to begin the installation process.

Post-installation you can verify the Jenkins service is running in the services. If you have any separate service account then you can choose “Run service as local or domain user” option during STEP 8 and provide the service account username &password instead of “run service as LocalSystem”.

Step 13: Unlock Jenkins

Type http://localhost:portno (here I configured with 8080 during the installation) in the browser. To ensure Jenkins is started securely by an administrator account, a password is written on C:\Windows\system32\config\systemprofile\AppData\Local\Jenkins\.jenkins\secrets\initialAdminPassword file needs to be given in the below screen to Continue.

Step 14: Choose the Customize Jenkins

You can choose either “Install suggested plugin” or “Select Plugins to install ” ( this option will not install any plugin and you can install based on your organization’s needs). For my setup, I have chosen the first option.

Step 15: Create an Admin User

You can also create an admin user account in case you don’t want to proceed as an admin. Here we are creating a user cyber hub and going to use the same for accessing Jenkins Server. In case you don’t want to create any user, you can click on Skip and continue as admin.

Step 16: Instance Configuration

Then you need to set up the Jenkins URL below Window. Here we will use the below default URL. So we leave it as it is and then click on Save and Finish.

Step 17: Using Jenkins in the browser

You will see a Jenkins Dashboard like below logged in with cyberithub account and now you can start creating your Job.

 

 

How to Convert YAML to JSON / JSON to YAML using PowerShell

A few days back my team member asked, Is there an easy way to convert YAML to JSON and JSON to YAML using scripts? As expected, my answer was: Yes, with PowerShell!

In some scenarios like in configuration management and Infrastructure as Code (IaC) spaces, use JSON or YAML files to store configuration data. This article is for you if you need to convert data from YAML to JSON format. In this article, you will learn ways to convert data YAML to JSON format & JSON to YAML format. To create the YAML to JSON conversion PowerShell script, follow these instructions. This PowerShell module is a thin wrapper on top of YamlDotNet that serializes and un-serializes simple PowerShell objects to and from YAML.

Converting YAML to JSON format:

STEP:1 Get the YAML file path and assign it to Variable

$YAMLFilePath = “C:\dotnet-helper\Build&Release.yml”

STEP:2 Get the YAML Content using Get-Content Cmdlet

$YAMLContent = Get-Content -Path $YAMLFilePath

STEP:3 Convert the YAML file to Hash Value using ConvertFrom-Yaml cmdlet

Read the YAML file using Get-Content and convert the data to a hashtable using ConvertFrom-Yaml (as shown below script).

hash_Value = ($YAMLContent | ConvertFrom-Yaml)

STEP:4 Convert the hashtable object to JSON format using ConvertTo-Json cmdlet & Finally save the file using Set-Content.

Set-Content -Path “C:\dotnet-helper\Build&Release.json” -Value ($hash_Value| ConvertTo-Json)

Full Code:

#Get the YAML file path and assign to Variable
$YAMLFilePath = "C:\dotnet-helpers\YML_Build&Release.yml"

#Get the YAML Content using Get-Content Cmdlet
$YAMLContent = Get-Content -Path $YAMLFilePath

#Convert the YAML file to Hash Value using ConvertFrom-Yaml cmdlet
$hash_Value = ($YAMLContent | ConvertFrom-Yaml)

#Convert the hashtable object to JSON format using ConvertTo-Json
#Finally save the save the file using Set-Content.
Set-Content -Path "C:\dotnet-helpers\JSON_Build&Release.json" -Value ($hash_Value| ConvertTo-Json)

OUTPUT:

Converting JSON to YAML format:

STEP:1 Get the JSON file path and assign it to Variable

$JsonFilePath = “C:\dotnet-helpers\JSON_Build&Release.JSON”

STEP:2 Get the JSON Content using Get-Content Cmdlet

$JsonContent = Get-Content -Path $JsonFilePath

STEP:3 Convert the JSON file to Hash Value using the ConvertFrom-Json cmdlet

Read the JSON file using Get-Content and convert the data to a hashtable using ConvertFrom-Json (as shown below script).

$hash_Value = ($JsonContent | ConvertFrom-Json)

STEP:4 Convert the hashtable object to YML format using ConvertTo-Yaml cmdlet & Finally save the file using Set-Content.

Set-Content -Path “C:\dotnet-helpers\YML_Build&Release.yml” -Value ($hash_Value| ConvertTo-Yaml)

Full Code:

#Get the JSON file path and assign to Variable
$JsonFilePath = "C:\dotnet-helpers\JSON_Build&Release.JSON"

#Get the YAML Content using Get-Content Cmdlet
$JsonContent = Get-Content -Path $JsonFilePath

#Convert the YAML file to Hash Value using ConvertFrom-Json cmdlet
$hash_Value = ($JsonContent | ConvertFrom-Json)

#Convert the hashtable object to YML format using ConvertTo-Yaml
Set-Content -Path "C:\dotnet-helpers\YML_Build&Release.yml" -Value ($hash_Value| ConvertTo-Yaml)

OUTPUT:

Passing Local Variables to Remote PowerShell session

While working with automation in remote computers using PowerShell, you’ll come across many scenarios where you may want to use local variables or input data in a remote session. But when you try to use a local variable in a remote session (inside the PowerShell script block), it may not work or may throw an error because the local variable doesn’t exist in the remote session. The same scenario I got in my automation which leads to writing this post.

To overcome the above scenario, PowerShell provides 3 way of methods to pass local variables to remote sessions. By using the below method, you can use them with Invoke-Command and New-PSSession to run the specific scripts inside the remote machine.

The script runs in a different scope on the remote system and it is not aware of the variables in the local session. In the example above, $local is actually $null in the remote session because it was never defined in that scope.

Note: Variables defined outside of Invoke-Command will not be available in the Invoke-Command scriptblock unless you explicitly pass them through or reference them.

  • -ArgumentList parameter
  • param() block
  • $using scope modifier

-ArgumentList parameter & Param block

One way to pass local variables to a remote scriptblock is to use the Invoke-Command ArgumentList parameter. This parameter allows you to pass local variables to the parameter and replace local variable references in the scriptblock with placeholders.

The $args variable is an automatic variable that contains an array of the undeclared parameters or parameter values passed to a function or a scriptblock. You can access the parameters passed to the scriptblock just like elements of an array( ArgumentList parameter is an object collection. Object collections allow you to pass one or more objects at a time.) In this example, I’m just passing one.

Example: 1 Using the $args automatic variable

$username = $serviceUsername $password = $servicePwd 
$buildNo = $BUILD_NUMBER 
$userPassword = ConvertTo-SecureString -String 
$password -AsPlainText -Force 
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $userPassword

$arguments = @("dotnet-helpers","powershell")
Invoke-Command -ComputerName $iP -ScriptBlock {
$args
foreach ($value in $args)
{
write-host $value
}
} -credential $userCredential -ArgumentList $arguments

Note: The first parameter passed to the scriptblock is $args[0], the second is $args[1], and so on. 

Example: 2 Using Param with -ArgumentList (Parameterized scriptblocks using param())

You can use param() blocks inside a function to accept parameters, but the only difference between a function and a scriptblock is that a function is named scriptblock. That means that just like in a function, we can use a param() block in a scriptblock. Then we will use this scriptblock with the Invoke-Command cmdlet and pass parameters through the -ArgumentList cmdlet.

$username = $serviceUsername
$password = $servicePwd
$buildNo = $BUILD_NUMBER

$userPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $userPassword

Invoke-Command -ComputerName $iP -ScriptBlock {

param($buildNo)
Write-host $buildNo

} -credential $userCredential -ArgumentList $buildNo

$Using Construct

From PowerShell 3, you can use local variables in remote sessions by utilizing the $Using modifier. The command uses the Using scope modifier to identify a local variable in a remote command.

$buildNo variable that is prefixed by the Using scope modifier to indicate that it was created in the local session, not in the remote session.

Example:

$buildNo = "2010"

Invoke-Command -ComputerName Server01 -ScriptBlock {

Write-host $Using:buildNo

}