powershell script best practices 1- Comments in the code

How To

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

Adding detailed comments that explain what is logic behind the code and why the code is written in that way. This can reduce confusion for other people (and sometime yourself ūüôā )¬† when trying to update code or troubleshooting code. your script will be much harder to read and understand by someone else without comments.

There are two way we can add comments as below: –¬†

Single line comment starting each line with # Comment

Block of comment text <# Comment  #> 

Apart from comments, you can also add script header with script detail , description, usage, author, Author contact, script version and initial draft/creation date. script header always help other to find out correct syntax/parameters to use the script/code and they can contact author in case any issue/doubts.

    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
    Email:      [email protected]**look.com #replace * with correct word
    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 $_"

Below are few more PS best practices :-

ps-click on links for more detail about each topic.

1> Comments -> Always use comments to explain code .. click for more detail

2> powershell logging –> log all possible detail to throubleshooting the script or check the script execution history.

3> Error handling -> custom and system error handling with with try-catch

4> Functions -> Powershell function to avoid duplicate code

5> Parameters or User-defined variables -> No Hard-Coding so better to keep all input as parameters for functions or Place user-defined variables at top of script in case required.

6> #regions -> Grouping of code with regions for easy reading and troubleshooting

7> beautify/ Auto indent powershell -> beautify and auto indent powershell code with visual studio code

(Visited 268 times, 1 visits today)