Skip to content

Instantly share code, notes, and snippets.

@ppanyukov
Created April 21, 2020 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ppanyukov/1ac7d9a5a8c04b216fc44e5672cce16d to your computer and use it in GitHub Desktop.
Save ppanyukov/1ac7d9a5a8c04b216fc44e5672cce16d to your computer and use it in GitHub Desktop.
powershell-azure-cli-demo
#!/usr/bin/env pwsh
# Very very small demo of Powerhell and how to use
# Azure CLI from within it.
# These should be required for all scripts.
# The first says to stop at any failure, almost same as bash 'set -e'
# except it does not apply to external commands unfortunately.
# The second one is to make sure informational messages are written.
# See: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7
$ErrorActionPreference = "Stop"
$InformationPreference = "Continue"
# Use this instead of echo
Write-Information "Demo for Powershell"
try {
# This normally terminates the script.
# But we can wrap it in try/catch
Write-Error "This will terminate the script"
} catch {
# $_ gets the error
Write-Information "Ingored the error: $($_)"
}
# Call out to Azure CLI and access JSON output in Powershell.
# Az CLI returns JSON by default. For 'az account show' it
# will be like so:
# {
# "environmentName": "REDACTED",
# "id": "REDACTED",
# "isDefault": true,
# "name": "REDACTED",
# "state": "Enabled",
# "tenantId": "REDACTED",
# "user": {
# "name": "REDACTED",
# "type": "user"
# }
# }
$x = &az account show | ConvertFrom-Json
if (!$?){
# Handle any errors like so. Equivalent to bash test for $?.
# Unfortunately there is no equivalent to bash 'set -e' for
# external commands
Write-Error "Error getting account information."
}
# If the above succeeded, get JSON properties like so
$userName = $x.user.name
Write-Information "Azure user name is: $userName"
Write-Information "This is the end of the short demo."
Write-Information "Good luck lol 🤣🤣😅🍺🍺"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment