【问题标题】:What is the correct way to detect whether a script is running in Azure Automation?检测脚本是否在 Azure 自动化中运行的正确方法是什么?
【发布时间】:2016-09-10 12:41:05
【问题描述】:

使用 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中运行时的机器名和用户名都是“Client”,这似乎是一种更健壮的方法?

【问题讨论】:

  • 刚刚想到了另一种方法。在AA中运行时,临时文件夹为c:\temp

标签: powershell azure-automation


【解决方案1】:

您可以使用您已经发现的用户名/计算机名称,或者您可以检查是否存在 Runbook 作业 ID:

if($PSPrivateMetadata.JobId) {
   # in Azure Automation
}
else {
   # not in Azure Automation
}

【讨论】:

  • 这不适用于 Azure 上的 PowerShell 7.1 运行时
【解决方案2】:

不确定是否有“正确的方法”,但如果您想检查是否在 Powershell ISE 中运行脚本,您可以检查$psISE-变量是否存在。

#same as if($psISE -ne $null) {...  
if($psISE) {
    #In PowerShell ISE
} else {
    #PowerShell console or Azure Automation
}

【讨论】:

  • 啊,好吧,反过来做 - 我明白了。
【解决方案3】:

适用于 PowerShell 5.1 和 7.1 的有效解决方案

this answer 中的$PSPrivateMetadata.JobId 不适用于带有 PowerShell 7.1 的 Azure 自动化 Runbook,因此我搜索了另一个解决方案,最终找到了合适的环境变量 ($env:AZUREPS_HOST_ENVIRONMENT)。

它在带有 PowerShell 5.1 和 PowerShell 7.1 的 Azure 自动化 Runbook 中返回“AzureAutomation/”,并且在本地环境中不存在。

if ("AzureAutomation/" -eq $env:AZUREPS_HOST_ENVIRONMENT) {
    # We are running in Azure Automation
}
else {
    # We are running locally
}

【讨论】:

    猜你喜欢
    • 2011-06-19
    • 2014-09-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2014-12-08
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多