0

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

我的目标是通过在azure automation中运行powershell代码来删除类型private创建时间超过2 天的所有资源。

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

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

这是我在 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.

在此处输入图像描述

4

2 回答 2

0

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

简单地做

$CreatedTime=$Tags['CreatedTime']

您可以使用 write-host 进行测试$Tags['CreatedTime'].GetType().FullName

于 2020-08-04T10:14:17.613 回答
0

有两点不对。

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

详情:

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

我的解决方案:

$AllRes = (get-AzResource -TagName "CreatedTime").ResourceId其他的 $AllRes = (get-AzureRMResource).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满足两种格式。

于 2020-08-06T09:31:07.950 回答