If you’re like me and work a lot with Azure Functions using a language like PowerShell, then this means a lot of testing and therefore also starting many PS modules individually. However, for this, I have to authenticate myself each time again. Now, it would be very convenient if a PowerShell script or, for example, a PS-function can run once, and not over and over again, without needing to log in each time. After all, I’m already signed in. By using the capabilities of functions within PowerShell, this can be done very easily.
Code: Run PS-function once
First script:
# Begin Dot-source the PS Variables.ps1 file
. "$PSScriptRoot\PS Variables.ps1"
. "$PSScriptRoot\PS WordPress Samples.ps1"
# End Dot-source the PS Variables.ps1 file
This script loads the variables from the file PS Variables.ps1 and the file PS WordPress Samples.ps1 using the function through dot-sourcing.
Second script:
# Begin loading PS Variables.ps1
$tenantId = not visible here
$subscriptionId = not visible here
# End loading PS Variables.ps1
This script defines the $tenantId
and $subscriptionId
variables that are needed for the Azure connection.
Third script to make sure PS-function only runs once
# Begin Function to log in to Azure
Function Login-Azure {
if (-not $global:connected) {
Connect-AzureAd -TenantId $tenantId -WarningAction SilentlyContinue | Out-Null
$global:connected = $true
Write-Host "Logon was successfull"
} else {
Write-Host "Logon has already been done. No further action needed"
}
}
# End Function to log in to Azure
This script defines a function Login-Azure
that logs in to various Azure services if no connection has yet been established. Use the variable $global:connected
to track whether a successful connection to Azure has already been made.
Why is making the variable global useful in PowerShell?
Prevent repeated login attempts by storing the connection status in a global variable. The script can then check whether a connection has already been made. If so, it won’t log in again, which saves time and system resources.
By avoiding unnecessary login attempts, the script runs more efficiently. This is especially important in environments where multiple scripts or functions run simultaneously.
Make the variable global so that it can be accessed and updated from different parts of the script—or even from other scripts running in the same session.
Fourth script:
# Begin usage function Login-Azure
Login-Azure
# End usage function Login-Azure
This script calls the Login-Azure
function to log in to Azure.
Dit script roept de Login-Azure functie aan om in te loggen op Azure.
More information about PowerShell can be found here. More information about the author of this blog post can be found here.