Setting Up PowerShell for Azure

Kristian Ranstrom
June 22, 2022
2 min read

I have wanted to start using PowerShell to script my common Azure routines for sometime.  I finally got some time to create some scripts to help with the process.

If you don't have the most recent version of PowerShell, you can download it from the Microsoft repo.

VARIOUS POWERSHELL COMMANDS

# see version of powershell
$PsVersionTable

# install azure powershell module
Install-Module -Name Az -AllowClobber

LOGGING IN

You will undoubtedly have to login to your Azure account in order to get access to your environment.  The following method will open a dialog with Microsoft's Active Directory and will allow you to walk through the authentication flow.

# connect to azure accounts to login
Connect-AzAccount

BASIC COMMANDS

Once it, you are then able to do various tasks like see your accounts, subscriptions and set a default subscription for future commands.

# get list of subscriptions after logged in
Get-AzSubscription

# set the default
Select-AzSubscription -Subscription 'MySubscriptionName'

# see the current default subscription
Get-AzContext

RUNNING SCRIPT (*.PS1) FILES

Often, you'll want to create a ps1 script file to run.  You can run this from the command line by just navigating to the directory it's in and then typing in the file name.

PS>cd /mydir
PS>./myfile.ps1

You may get an error saying that the file will not run because the ExecutionPolicy disallows it.  You can override this during the session by using this command:

# See the execution policy on your computer
Get-ExecutionPolicy -List

# Set the execution policy for the session. 
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Once that is set, you can rerun the ps1 file and you should not get the error again.

HELPFUL NOTES

It's also of note that any commands that use the “AzureRM” module are discontinued, so stay away from those.  The commands you should be using just have “Az” in the command name, such as “Get-AzSubscription” and not “Get-AzureRMSubscription”.