简体   繁体   中英

Azure Runbooks Issue

I've included my code below... All i'm trying to do is loop this runbook through specific subscriptions in our Azure environment and have it report on the backups performed in these subscriptions. When testing it in Powershell ISE it works perfectly fine. In runbooks not at all, it also doesn't give me any errors so no idea whats happening.... Please HELP!

$connectionName = "AzureRunAsConnection"

try{
    #Getting the service principal connection "AzureRunAsConnection"
    $servicePrincipalConnection = Get-AutomationConnection -name $connectionName

    "Logging into Azure..."
    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
    }
}

if($err) {
throw $err
}

Import-Module Az.Accounts

function Send-Email() {

    Write-Output "Sending an email"
    $Username ="mymailaccount@azure.com" # Your user name - found in sendgrid portal
    $Password = ConvertTo-SecureString "password" -AsPlainText -Force # SendGrid Password
    $credential = New-Object System.Management.Automation.PSCredential $Username, $Password
    $SMTPServer = "smtp.sendgrid.net"
    $EmailFrom = "Emailfrom" # Can be anything - aaa@xyz.com
    $EmailTo = "EmailTo" # Valid recepient email address
    $Subject = "Azure Audit Report"
    $Body = "Summary as of: " + (Get-Date -Format G) + " UTC"+ "`n`n" + ($Data | Out-String)


    Send-MailMessage -smtpServer $SMTPServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body -Attachments $filename

}

$Data = @()

"Selecting Subscriptions.."
$AzureSubscriptions = Get-AzSubscription | Where-Object -Property name -Match "TheOne"

"Looping Through Subscriptions..."

foreach($Subscription in $AzureSubscriptions) #Loop through all Subscriptions
    {
    Select-AzSubscription -SubscriptionObject $Subscription
    $RSVaults = Get-AzRecoveryServicesVault | ?{$_.Name -notin @($ExcludeVault)}#Get Backup Vaults 

        foreach($Vault in $RSVaults)
        {
        Set-AzRecoveryServicesVaultContext -Vault $Vault
            #Process each Vault
        $DebugPreference = 'Continue'
        Get-AzRecoveryServicesBackupJob 5>"$($FolderPath)\Debug.log" | %{  $Data +=   [PSCustomObject]@{
                                                                                Subscription = $Subscription.Name
                                                                                Vault = $Vault.Name
                                                                                VMName = $_.WorkloadName
                                                                                StartTime = $_.StartTime
                                                                                EndTime = $_.EndTime
                                                                                Duration = $_.Duration
                                                                                Status =  $_.Status
                                                                                                            }
                                                                               }


        #MARS Agent backup , currently only works with Debug info - Should be supported in the Future
        $D_i = 0 #Debug Object set
        $D_Obj = @{Subscription = $Subscription.Name
                   Vault = $Vault.Name
                   VMName = ''
                   StartTime = ''
                   EndTime = ''
                   Duration = ''
                   Status =  ''
                  }
        Foreach ($str in @(Get-Content .\Debug.log))
                {
                $a_Str = (($str.Replace('"','').replace(",","").trim()) -split ' ')[1]
                    If ($str -like '*"jobType": "MabJob",*')
                        {$D_i = 1}

                    If ($Str -like '*"duration":*' -and $D_i -eq 1)
                        {$D_Obj.'Duration' =  $a_Str}

                    If ($Str -like '*"mabServerName":*' -and $D_i -eq 1)
                        {$D_Obj.'VMName' =  $a_Str}

                    If ($Str -like '*"status":*' -and $D_i -eq 1)
                        {$D_Obj.'Status' =  $a_Str}

                    If ($Str -like '*"startTime":*' -and $D_i -eq 1)
                        {$D_Obj.'StartTime' =  [datetime]$a_Str}   

                    If ($Str -like '*"endTime":*' -and $D_i -eq 1)
                        {$D_Obj.'EndTime' =  [datetime]$a_Str

                        $Data  += [pscustomobject]$D_Obj

                        $D_i = 0
                        #Reset the Object
                        $D_Obj = @{Subscription = $Subscription.Name
                           Vault = $Vault.Name
                           VMName = ''
                           StartTime = ''
                           EndTime = ''
                           Duration = ''
                           Status =  ''
                           }
                        }  

                  }


        }
    }


#Region HTML Report
$css = @"
<Title>Azure Backup Report: $(Get-Date -Format 'dd MMMM yyyy' )</Title>
<Style>
th {
    font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica,
    sans-serif;
    color: #FFFFFF;
    border-right: 1px solid #C1DAD7;
    border-bottom: 1px solid #C1DAD7;
    border-top: 1px solid #C1DAD7;
    letter-spacing: 2px;
    text-transform: uppercase;
    text-align: left;
    padding: 6px 6px 6px 12px;
    background: #5F9EA0;
}
td {
    font: 11px "Trebuchet MS", Verdana, Arial, Helvetica,
    sans-serif;
    border-right: 1px solid #C1DAD7;
    border-bottom: 1px solid #C1DAD7;
    background: #fff;
    padding: 6px 6px 6px 12px;
    color: #6D929B;
}
</Style>
"@

[string]$FileName = "AzureBackupReport$(Get-date -f ddMMyyyy).html"
$Report = $Data | ConvertTo-Html -Head $css; $Report |Out-File "$filename"


"Done."


Send-Email

When you execute a script as Azure Automation runbook, I suggest you to save the AzureBackupReport$(Get-date -f ddMMyyyy).html file in $env:temp and also for sending email, I suggest you to use Invoke-RestMethod cmdlet instead of Send-MailMessage cmdlet because as per this Azure document Invoke-RestMethod cmdlet approach is suggested to use for sending an email from an Azure Automation runbook.

Same Azure document also has an example runbook for reference so I suggest you to check it as reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM