【问题标题】:Failed when running powershell code in azure automation在 azure 自动化中运行 powershell 代码时失败
【发布时间】:2020-11-24 08:13:56
【问题描述】:

我设置了一个 azure 策略,添加了两个标签,即 CreatedTimeTypeCreatedTime的值为utcNow(),默认格式为'yyyy-MM-ddTHH:mm:ss.fffffffZ'.

我的目标是通过运行 删除所有 Typeprivatecreated time 长于 2 天 的资源azure 自动化 中的 powershell 代码。

我已经在 locally 的 power shell 中完成了它,但是当我在 automation 中运行代码时,它失败了。我将在下面发布代码和错误页面。

谁能告诉我我的代码有什么问题?还是我错过了什么?

这是我在 Azure 自动化中的代码:

   $connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint 
$servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

    $AllRes = (get-AzureRMResource).ResourceId
    $TimeOutDays=2
    foreach ($Res in $AllRes){
    $Resource = Get-AzureRMResource -ResourceId $Res
    $Tags=$Resource.Tags
    $TypeInTags=$Tags['Type']
    $CreatedTimeInTags=$Tags['CreatedTime']
try{
    $CreatedTime=[Datetime]::ParseExact($CreatedTimeInTags, 'MM/dd/yyyy HH:mm:ss', $null)
}
catch{
    $CreatedTime=[Datetime]::ParseExact($CreatedTimeInTags, 'yyyy-MM-ddTHH:mm:ss.fffffffZ', $null)
}
finally
{
    $CreatedTime
}
    $daypan=((get-date)-$CreatedTime).Days
    if($TypeInTags -eq 'private')
    {
    if($daypan -gt $TimeOutDays)
        {
            $daypan
            Remove-AzureRMResource -ResourceId $Res -Force
        }
    }
}

这是错误页面: 暂停

The runbook job was attempted 3 times, but it failed each time.  Common reasons that runbook jobs fail can be found here:  https://docs.microsoft.com/en-us/azure/automation/automation-troubleshooting-automation-errors

一条错误信息:

Get-AzureRMResource : ResourceNotFound : The Resource 
'microsoft.alertsmanagement/smartDetectorAlertRules/Failure+Anomalies+-+arrowbottest2-config' under resource group 
'arrowbot2' was not found. For more details please go to https://aka.ms/ARMResourceNotFoundFix
At line:28 char:17
+     $Resource = Get-AzureRMResource -ResourceId $Res
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureRmResource], ErrorResponseMessageException
    + FullyQualifiedErrorId : 
ResourceNotFound,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet
 
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:34 char:5
+     $CreatedTime=[Datetime]::ParseExact($Tags['CreatedTime'], 'yyyy-M ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException
 
Cannot find an overload for "op_Subtraction" and the argument count: "2".
At line:35 char:5
+     $daypan=((get-date)-$CreatedTime).Days
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest
 

Cannot find an overload for "op_Subtraction" and the argument count: "2".
At line:35 char:5
+     $daypan=((get-date)-$CreatedTime).Days
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest
 
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:34 char:5
+     $CreatedTime=[Datetime]::ParseExact($Tags['CreatedTime'], 'yyyy-M ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

对于$Tags['CreatedTime']的类型,我这样做是为了测试:$Tags['CreatedTime'].GetType().FullName

【问题讨论】:

  • 你能把$CreatedTimeInTags的输出贴出来
  • 你的意思是$CreatedTimeInTags在自动化中的输出吗?
  • 是的。看起来日期的解析失败了,你可以只发布变量的输出吗?
  • 如果您将解析日期的行替换为以下内容,也许一切正常:[datetime]$CreatedTime = $Tags['CreatedTime']
  • 好的,我正在重新运行这段代码,这需要一些时间,请稍等。

标签: azure powershell azure-automation runbook


【解决方案1】:

既然你说 CreatedTime 的值是utcNow(),那么那个值已经是一个 DateTime 对象,你不应该把它当作字符串。 (你认为它是一个字符串,因为当你把它写到控制台时,它会显示它的ToString() 表示)

简单地做

$CreatedTime=$Tags['CreatedTime']

您可以使用写入主机 $Tags['CreatedTime'].GetType().FullName 对此进行测试

【讨论】:

  • @DorisLv 那么,Write-Host $Tags['CreatedTime'].GetType().FullName 透露了什么? (请不要每次都评论诸如不起作用之类的东西。解释发生了什么并将问题中的完整异常添加为格式化文本。)
  • 我已经更新了我的问题中的代码。我之前尝试过您的建议,但出现了同样的错误。即使我设置了标记的值 utcNow(),但当我这样做时,它会指向一个不是 DateTime 对象的字符串:$CreatedTimeInTags=$Tags['CreatedTime']
  • @DorisLv 请告诉我们你在Write-Host $Tags['CreatedTime'].GetType().FullName时得到了什么。我仍然相信它是 NOT 作为字符串,而是一个 DateTime 对象。您只是没有检查类型,因此只看到日期的字符串表示形式。
  • 我在我的问题正文中更新了一张图片,您可以清楚地看到。 @Theo
【解决方案2】:

有两件事不对。

1.没有指定我需要的资源。

详情:

这就是错误消息的原因:Can not index to a null array.我遍历了订阅中的整个资源,但是 在我设置策略之前创建的资源没有名为 "CreatedTime""Type",所以当我运行 $Tags=$Resource.Tags 时,它 说Can not index to a null array.

我的解决方案:

除了$AllRes = (get-AzureRMResource).ResourceId 之外,执行$AllRes = (get-AzResource -TagName "CreatedTime").ResourceId。 我发现 AzureRM 模块没有 将-TagName 识别为变量,因此我导入了 Az 模块并 将每个 AzureRM 模块更改为 Az 模块。

2.与 utcNow() 混淆。

详情:

正如我所说,使用 utcNow() 函数我得到一个默认的 DateTime 对象 格式'yyyy-MM-ddTHH:mm:ss.fffffffZ',经过大量测试, 我发现了一些特殊资源,例如应用程序洞察力的标签值是 不是用'yyyy-MM-ddTHH:mm:ss.fffffffZ' 格式化的,当我打电话时 它,它是一个字符串。

我的解决方案:

所以当我使用它与get-date 相比时,我 需要做两件事:

(1)将字符串改为DateTime对象;

(2)使用try-catch满足两种格式。

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多