0
votes

Last week, I deployed a script to backup some disks using the New-AzSnapshot cmdlet. I scheduled this script in the Azure Automation Account and for the first 2 days, the script worked very well!

Today, I analyzed the logs and saw that the script had the error below:

Connect-AzAccount : Object reference not set to an instance of an object. At line:12 char:25 + $connectionResult = Connect-AzAccount ` + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Connect-AzAccount], NullReferenceException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

Does anyone have any idea what may be causing this error?

Below the script:

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." 
    } 
}
1

1 Answers

0
votes

You're having a nullreference exception, looking at the location inside the error message (At line:12 char:25). it shows that connection is null.

You need to declare connection first on the same page before you're able to use the variables inside.

See also: What is a NullReferenceException, and how do I fix it?

EDIT: At second notice, I think that you're already declaring the $connection at

$connection = Get-AutomationConnection -Name AzureRunAsConnection

but it looks like that's returning null. In that case, you'll need to figure out why that's returning null, because it should return a filled $connection if connected.

For a safe check to avoid errors: you should check first if the $connection is not null before entering the while, (for example $connection != null could work for Javascript). That way you won't get errors, but keep in mind that you won't get a result through this.