Azure sign-in methods in PowerShell script

Posted by John Liu on Monday, November 1, 2021

When using PowerShell script to run tasks in Azure environment, we need first to sign-in to Azure. There are several ways to sign-in to Azure in PowerShell script.

1. Interactive sign-in

we can using either

Connect-AzAccount

or

Login-AzAccount -Credential (Get-Credential)

Login-AzAccount and Add-AzAccount are alias of Connect-AzAccount. With -Credential (Get-Credential) option, it let you interactively enter the credential on the cmd interface, otherwise, it popup a GUI to let you login.

However, when run PowerShell script unattended, we can’t use interactive sign-in.

2. password file

For unattended automation script, we can store credential securely in a text file.

(Get-Credential).password | ConvertFrom-SecureString | set-content "C:\temp\password.txt"

The above command prompt you for the credential information and store the entered credential into password.txt file as an encrypted string. We then can read this encrypted string in our script like following

$pwdfile = "C:\temp\password.txt"
$UserName = "your user name"
$Password = Get-Content $pwdfile | ConvertTo-SecureString
$Credential = New-object System.Management.Automation.PsCredential($UserName, $Password)
Connect-AzAccount -Credential $Credential

3. use profile to switch context

You can create a profile using PowerShell console or via Cloud Shell in Azure Portal. To create profile using PowerShell console, first sign-in to Azure using the credential you want to create the profile for.

Connect-AzAccount

Once singed in, run following command to create profile. If no file path specified, the profile will be created under current folder.

Save-AzProfiel -Path C:\temp\MyAzureProfile.json

To switch the session context using the above created profile

$profile = Import-AzContext -Path C:\temp\MyAzureProfile.json
$SubscriptionID = $profile.Context.Subscription.SubscriptionID
Set-AzContext -SubscriptionId $SubscriptionID