Azure自动化帐户-Runbook错误-对象引用未设置为对象的实例



上周,我部署了一个脚本来使用New-AzSnapshot cmdlet备份一些磁盘。我在Azure自动化帐户中安排了这个脚本,在前两天,这个脚本运行得很好!

今天,我分析了日志,发现脚本出现了以下错误:

Connect AzAccount:对象引用未设置为对象的实例。在第12行,char:25+$connectionResult=Connect-AzAccount`+~~~~~~ ~~~~+类别信息:CloseError:(:([Connect AzAccount],NullReferenceException+FullyQualifiedErrorId:Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

有人知道是什么原因导致了这个错误吗?

脚本下方:

Param(
[string]$resourceGroupName
)
$connection = Get-AutomationConnection -Name AzureRunAsConnection
while (!($connectionResult) -And ($logonAttempt -le 10)) {
$LogonAttempt++
# Logging in to Azure...
$connectionResult = Connect-AzAccount `
-ServicePrincipal `
-Tenant $connection.TenantID `
-ApplicationID $connection.ApplicationID `
-CertificateThumbprint $connection.CertificateThumbprint
Start-Sleep -Seconds 30
}
# Remove old snapshots
$snapshotnames = (Get-AzSnapshot -ResourceGroupName $resourceGroupName).name
foreach($snapname in $snapshotnames)
{
Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapname | ?{($_.TimeCreated) -lt ([datetime]::UtcNow.AddMinutes(-10080))} | Remove-AzSnapshot -Force
} 
foreach ($VMs in Get-AzVM -ResourceGroupName $resourceGroupName) {  
#Set local variables 
$location = $VMs.Location 
#$resourceGroupName = $vmInfo.ResourceGroupName 
$timestamp = Get-Date -f MM-dd-yyyy_HH_mm_ss 
#Snapshot name of OS data disk 
$snapshotName = "bkp-" + $VMs.Name + "-" + $timestamp 
#Create snapshot configuration 
$snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.OsDisk.ManagedDisk.Id -Location $location  -CreateOption copy 
#Take snapshot 
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName  

if ($VMs.StorageProfile.DataDisks.Count -ge 1) { 
#Condition with more than one data disks 
for ($i = 0; $i -le $VMs.StorageProfile.DataDisks.Count - 1; $i++) { 
#Snapshot name of OS data disk 
$snapshotName = "bkp-" + $VMs.StorageProfile.DataDisks[$i].Name + "-" + $timestamp
#Create snapshot configuration 
$snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.DataDisks[$i].ManagedDisk.Id -Location $location  -CreateOption copy 
#Take snapshot 
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName  
} 
} 
else { 
Write-Host $VMs.Name + " doesn't have any additional data disk." 
} 
}

您有一个nullreference异常,正在查看错误消息中的位置(第12行,字符:25(。则表明CCD_ 1为空。

您需要先在同一页上声明connection,然后才能使用其中的变量。

另请参阅:什么是NullReferenceException,以及如何修复它?

编辑:第二次通知时,我认为您已经在上声明了$connection

$connection = Get-AutomationConnection -Name AzureRunAsConnection

但看起来它正在返回null。在这种情况下,您需要弄清楚为什么返回null,因为如果连接,它应该返回一个填充的$connection

为了避免错误的安全检查:在输入while之前,您应该首先检查$connection是否不为null(例如$connection != null可以用于Javascript(。这样你就不会犯错误,但要记住,通过这种方式你不会得到结果。

最新更新