运行 天蓝色自动化中的 powershell 代码时失败
Failed when running powershell code in azure automation
我设置了 azure 策略 添加两个标签,即 CreatedTime
和 Type
。
CreatedTime
的值为utcNow()
,默认格式为'yyyy-MM-ddTHH:mm:ss.fffffffZ'.
我的目标是删除所有 Type 为 private
且 created time 长于 的资源]2 天 运行ning powershell azure automation.
中的代码]
我已经在 power shell locally 中完成了,但是当我 运行 automation 中的代码时,它失败了。我将 post 下面的代码和错误页面。
谁能告诉我我的代码有什么问题?或者我错过了什么?
这是我在 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
.
既然你说 CreatedTime 的值是 utcNow()
,那么这个值已经是一个 DateTime 对象,你不应该把它当作字符串。 (你认为它是一个字符串,因为当你把它写到控制台时,它会显示它的ToString()
表示)
简单做
$CreatedTime=$Tags['CreatedTime']
您可以使用 write-host $Tags['CreatedTime'].GetType().FullName
进行测试
有两点不对。
1.Didn没有指定我需要的资源。
详情:
这就是错误消息的原因:Can not index to a null array.
我遍历了订阅中的整个资源,但是
在我设置策略之前创建的资源没有名为
"CreatedTime"
or "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.Confused 与 utcNow().
详情:
正如我所说,使用 utcNow() 函数我得到一个默认的 DateTime 对象
格式 'yyyy-MM-ddTHH:mm:ss.fffffffZ'
,经过大量测试,
我发现一些特殊资源,如 application insight 的标签值是
未使用 'yyyy-MM-ddTHH:mm:ss.fffffffZ'
格式化,当我调用
它,就到了一个字符串。
我的解决方案:
所以当我使用它时与 get-date
相比,我
需要做两件事:
(1)将字符串改为DateTime对象;
(2)使用try-catch满足两种格式
我设置了 azure 策略 添加两个标签,即 CreatedTime
和 Type
。
CreatedTime
的值为utcNow()
,默认格式为'yyyy-MM-ddTHH:mm:ss.fffffffZ'.
我的目标是删除所有 Type 为 private
且 created time 长于 的资源]2 天 运行ning powershell azure automation.
我已经在 power shell locally 中完成了,但是当我 运行 automation 中的代码时,它失败了。我将 post 下面的代码和错误页面。
谁能告诉我我的代码有什么问题?或者我错过了什么?
这是我在 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
.
既然你说 CreatedTime 的值是 utcNow()
,那么这个值已经是一个 DateTime 对象,你不应该把它当作字符串。 (你认为它是一个字符串,因为当你把它写到控制台时,它会显示它的ToString()
表示)
简单做
$CreatedTime=$Tags['CreatedTime']
您可以使用 write-host $Tags['CreatedTime'].GetType().FullName
有两点不对。
1.Didn没有指定我需要的资源。
详情:
这就是错误消息的原因:Can not index to a null array.
我遍历了订阅中的整个资源,但是
在我设置策略之前创建的资源没有名为
"CreatedTime"
or "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.Confused 与 utcNow().
详情:
正如我所说,使用 utcNow() 函数我得到一个默认的 DateTime 对象
格式 'yyyy-MM-ddTHH:mm:ss.fffffffZ'
,经过大量测试,
我发现一些特殊资源,如 application insight 的标签值是
未使用 'yyyy-MM-ddTHH:mm:ss.fffffffZ'
格式化,当我调用
它,就到了一个字符串。
我的解决方案:
所以当我使用它时与 get-date
相比,我
需要做两件事:
(1)将字符串改为DateTime对象;
(2)使用try-catch满足两种格式