powershellazurepowershell-workflowrunbook

Running a power shell script in Azure


Hi there I'm new to running powershell scripts in azure and looking for the best guidance ?

I have created a powershell script to locate running machines in a resource group and output to a text file,

what would be the best approach to schedule this script to run autonomously in azure ?

Script below:

#Login-AzureRmAccount 
#$sub = Get-AzureRmSubscription | Out-GridView -PassThru | Set-AzureRmContext

$path="dcsppomsstorage.blob.core.windows.net/dcsvmpowerstate/activeserver1.txt"
function SPWservers {

[string]$ResourceGroupName = "*DCS-PP*"


$VMresourcegroups = (Get-AzureRmResourceGroup).Where({$_.ResourceGroupName -like $ResourceGroupName})
foreach($VMresourcegroup in $VMresourcegroups){
$vms=Get-AzureRmVM -ResourceGroupName $VMresourcegroup.ResourceGroupName
foreach ($vm in $vms)
{

$Status = (get-azurermvm -ResourceGroupName $VMresourcegroup.ResourceGroupName -Name $vm.Name -Status).Statuses

Write "powerstate for $($vm.Name) is $($Status[1].DisplayStatus)" | Format-Table $vm.Name, $Status[1].DisplayStatus -GroupBy $vm.name

}
}
}




SPWservers| out-file $path

Solution

  • As Bruno Faria said, we can use Azure Automation to do that.

    But for now, we can't save the runbook job's output to Azure storage blob direct.

    As a workaround, we can check the output in Azure portal. Script like this:

    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
    function SPWservers {
    [string]$ResourceGroupName = "vms"
    $VMresourcegroups = (Get-AzureRmResourceGroup).Where({$_.ResourceGroupName -like $ResourceGroupName})
    foreach($VMresourcegroup in $VMresourcegroups){
    $vms=Get-AzureRmVM -ResourceGroupName $VMresourcegroup.ResourceGroupName
    foreach ($vm in $vms)
    {
    
    $Status = (get-azurermvm -ResourceGroupName $VMresourcegroup.ResourceGroupName -Name $vm.Name -Status).Statuses
    
    Write "powerstate for $($vm.Name) is $($Status[1].DisplayStatus)" | Format-Table $vm.Name, $Status[1].DisplayStatus -GroupBy $vm.name
    
    }
    }
    }
    
    SPWservers| write-output
    

    After this runbook job completed, we can find the output here:

    enter image description here

    About Azure runbook schedules, we can set it here:

    enter image description here

    More information about scheduling a runbook in Azure automation, please refer to this article.