0

我编写了以下 Runbook 工作流程,但在尝试启动或停止 VM 时有时会看到错误:

Start-AzVM :您的 Azure 凭据尚未设置或已过期,请运行 Connect-AzAccount 以设置您的 Azure 凭据。在 StartStopVmByTag:46 char:46 + + CategoryInfo : CloseError: (:) [Start-AzVM], ArgumentException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.StartAzureVMCommand

我已经尝试传入 $azContext 变量,但我仍然遇到这个问题,我该如何进一步调查?

workflow StartStopVmByTag {
    $connectionName = "AzRunAsConnection2042";

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

        Write-Output "Logging in to Azure..."
        $null = Add-AzAccount `
            -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
        }
    }

    [DateTime]$now = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'GMT Standard Time')
    $startTag = 'Start Schedule'

    Write-Output "*** $now - Runbook Started  ***"

    # Get Subscriptions
    $Subscriptions = Get-AzSubscription

    ForEach ($Subscription in $Subscriptions) {
        $azContext = Set-AzContext -SubscriptionId $Subscription.Id

        # Get all VM's with a Start or Stop Schedule
        Write-Output "$($Subscription.Name): Getting VM's..."
        [Array]$taggedVms = Get-AzResource -TagName $startTag -ResourceType 'Microsoft.Compute/virtualMachines'
        $taggedVms = $taggedVms | Sort-Object -Property Name -Unique

        # For each VM, check if start schedule is valid for now
        Foreach -Parallel ($taggedVm in $taggedVms) {
            Write-Output "$($Subscription.Name): Found Tagged VM: $($taggedVm.Name), $($startTag): $($taggedVm.Tags.$startTag -replace '\s', '')"
            $WORKFLOW:null = Start-AzVM -ResourceGroupName $taggedVm.ResourceGroupName -Name $taggedVm.Name -DefaultProfile $azContext -NoWait
        }
    }
}
4

0 回答 0