Thursday, December 24, 2015

Check if there is already a login session in Azure Powershell.

function Check-Session () {
    $Error.Clear()

    #if context already exist
    Get-AzureRmContext -ErrorAction Continue
    foreach ($eacherror in $Error) {
        if ($eacherror.Exception.ToString() -like "*Run Login-AzureRmAccount to login.*") {
            Login-AzureRmAccount
        }
    }

    $Error.Clear();
}

#check if session exists, if not then prompt for login
Check-Session


2 comments:

  1. I've done the same thing as a try/catch statement:

    Try
    {
    Get-AzureRmContext -ErrorAction Continue
    }
    Catch [System.Management.Automation.PSInvalidOperationException]
    {
    Login-AzureRmAccount
    }

    ReplyDelete