Comments in powershell script/code is very important to explain the code.

Adding detailed comments that explain what you are doing and whay the code is wrriten in that way. This can reduce confusion for other people (and sometime yourself 🙂 ) trying to figure out how and why specific code/command was used. your script will be much harder to read and understand by someone else without comments.

In the following detailed comment example, we have used two comment types.

Single line comment starting each line with # Comment

Block of comment text <# Comment  #> 

    This script move Azure vm to another subscription/ resource group.
    - re-create Azure vm in another subscription / resource group.
	- re-create Azure vm in same subscription another resource group.
    Author:     Arun Sabale
    Created:    16-02-2021
    Version:    1.0
    [Parameter(mandatory = $True)]
    [Parameter(mandatory = $True)]
    [Parameter(mandatory = $True)]

    [Parameter(mandatory = $false)]

<# if you have multiple subscriptions then you can get source and target subscription-
ID from param. in that case you must have to remove line 38, 41 and add the $sourceSubscriptionID 
and $targetSubscriptionId inside param section on line 19 #>

#get the source subscription from automation variable
$sourceSubscriptionID = Get-AutomationConnection -Name "sourceSubscriptionID"

#get the target subscription to move azure VM from automation variable
$targetSubscriptionId=Get-AutomationConnection -Name "targetSubscriptionId"

# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection = Get-AutomationConnection -Name "AzureRunAsConnection" 

try {
        # Logging in to Azure with AzureRunAsConnection
        Write-Output "Logging in to Azure..."
        Add-AzAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
            -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
        # in case login failed then write error in output
        Write-Output "Failed to login in Azure..."
        if (!$servicePrincipalConnection) {
            $ErrorMessage = "Connection $connectionName not found."
            throw $ErrorMessage
            Write-Output $ErrorMessage
        else {

            throw $_
            Write-Output "ErrorMessage is $_"

(Visited 53 times, 1 visits today)

By Arun Sabale

Arun is a Solution Architect on enterprise client management with more than 14 years of experience in IT. Arun Sabale is Blogger and tech enthusiast. His main focus is on Azure cloud infra, Cloud automation with powershell, python, ARM terraform and all cloud infra services like compute, storage, network, automation, function api etc... LinkedIN -