在 Azure 自动化中检测脚本是否为 运行 的正确方法是什么?
What is the correct way to detect whether a script is running in Azure Automation?
使用 Azure 自动化开发 PowerShell 脚本可能会非常缓慢。使用 PowerShell ISE 插件可以帮助您在本地测试 运行 脚本。
但是,不可避免地,运行在本地与 运行在 Azure 自动化中进行时,有些事情会有所不同。例如文件路径。
检测脚本当前运行所在环境的正确方法是什么?
目前我定义了一个只保留在本地不上传的可变资产。然后我可以做类似的事情:
# Check if we are running locally - NOTE: Do not upload the runningLocally variable! Keep it local only
if (Get-AutomationVariable -Name 'runningLocally') {
# We are running locally
} else {
# We are running in Azure Automation
}
但这看起来相当笨拙且容易出错。我正在寻找更稳健可靠的方法。
我发现了一些额外的方法。 AA中运行ning时的机器名和用户名都是"Client",这个方法好像比较稳健?
不确定是否有 "correct way",但如果您想检查您是否 运行 Powershell ISE 中的脚本,您可以检查 $psISE
变量是否存在.
#same as if($psISE -ne $null) {...
if($psISE) {
#In PowerShell ISE
} else {
#PowerShell console or Azure Automation
}
您可以为此使用您已经发现的用户名/计算机名称,或者您可以检查是否存在 Runbook 作业 ID:
if($PSPrivateMetadata.JobId) {
# in Azure Automation
}
else {
# not in Azure Automation
}
PowerShell 5.1 和 7.1 的工作解决方案
来自 的 $PSPrivateMetadata.JobId
不适用于使用 PowerShell 7.1 的 Azure Automation Runbook,因此我搜索了另一个解决方案并最终找到了合适的环境变量 ($env:AZUREPS_HOST_ENVIRONMENT
)。
它 returns 'AzureAutomation/' 在带有 PowerShell 5.1 和 PowerShell 7.1 的 Azure Automation Runbooks 中,并且在本地环境中不存在。
if ("AzureAutomation/" -eq $env:AZUREPS_HOST_ENVIRONMENT) {
# We are running in Azure Automation
}
else {
# We are running locally
}
使用 Azure 自动化开发 PowerShell 脚本可能会非常缓慢。使用 PowerShell ISE 插件可以帮助您在本地测试 运行 脚本。
但是,不可避免地,运行在本地与 运行在 Azure 自动化中进行时,有些事情会有所不同。例如文件路径。
检测脚本当前运行所在环境的正确方法是什么?
目前我定义了一个只保留在本地不上传的可变资产。然后我可以做类似的事情:
# Check if we are running locally - NOTE: Do not upload the runningLocally variable! Keep it local only
if (Get-AutomationVariable -Name 'runningLocally') {
# We are running locally
} else {
# We are running in Azure Automation
}
但这看起来相当笨拙且容易出错。我正在寻找更稳健可靠的方法。
我发现了一些额外的方法。 AA中运行ning时的机器名和用户名都是"Client",这个方法好像比较稳健?
不确定是否有 "correct way",但如果您想检查您是否 运行 Powershell ISE 中的脚本,您可以检查 $psISE
变量是否存在.
#same as if($psISE -ne $null) {...
if($psISE) {
#In PowerShell ISE
} else {
#PowerShell console or Azure Automation
}
您可以为此使用您已经发现的用户名/计算机名称,或者您可以检查是否存在 Runbook 作业 ID:
if($PSPrivateMetadata.JobId) {
# in Azure Automation
}
else {
# not in Azure Automation
}
PowerShell 5.1 和 7.1 的工作解决方案
来自$PSPrivateMetadata.JobId
不适用于使用 PowerShell 7.1 的 Azure Automation Runbook,因此我搜索了另一个解决方案并最终找到了合适的环境变量 ($env:AZUREPS_HOST_ENVIRONMENT
)。
它 returns 'AzureAutomation/' 在带有 PowerShell 5.1 和 PowerShell 7.1 的 Azure Automation Runbooks 中,并且在本地环境中不存在。
if ("AzureAutomation/" -eq $env:AZUREPS_HOST_ENVIRONMENT) {
# We are running in Azure Automation
}
else {
# We are running locally
}