How to write pre/post-scripts for Azure VMs?

100 views Asked by At

I am trying to set up pre/post-scripts for our new patching system. The VMs need a tag added and turned on and then restarted and removed after. I don't have the roles to test just to get it done. Previous scripts I've seen to start our servers use functions-is this necessary? Very new to PowerShell and learning as I go so to speak curious about how the code looks/would run.

##########################  ADDITION  ##################################
$credentials = Import-Clixml -Path xxxxx
Connect-AzAccount -Tenant xxxxx-xxxxx-xxxxx-xxx-xxxxxxxx-Credential $credentials
Set-AzContext -Subscription "xxxxx"

#Append 'AutoScaleIgnore' tag with 'Patching' value to $tags list
$tags += @{AutoScaleIgnore="Patching"}

#Get AVD's in the UAT or DEV environments
$rs = Get-AzVM | where {($_.Tags['AVD'] -eq "AVD" -and $_.Tags['Environment'] -eq "DEV") -or ($_.Tags['AVD'] -eq "AVD" -and $_.Tags['Environment'] -eq "UAT")}

#Add autoscaleignore tag to each machine
foreach($r in $rs){
    New-AZTag -Name $r.Name -ResouceGroupName $r.ResourceGroupName -Tag $tags
}

########################## POWER ON ####################################
#Get all machines the AutoScaleIgnore tag exists on
$asi = Get-AzVM | where {($_.Tags['AutoScaleIgnore'] -eq "") -or ($_.Tags['AutoScaleIgnore'] -eq "Patching")}

#Make sure all of those machines are turned on for patching
foreach($a in $asi){
    Start-AzVM -Name $a.name -ResourceGroupName $a.ResourceGroupName -NoWait
}
########################################################################
##############################  POST-SCRIPT  #############################
###############################  RESTART VM  #############################
$credentials = Import-Clixml -Path xxxxx
Connect-AzAccount -Tenant xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx -Credential $credentials
Set-AzContext -Subscription "xxxxx"

$a = $env:computername
$a = Get-AzVM -Name $a
Restart-AzVM -Name $a.name -ResourceGroupName $a.ResourceGroupName

################################  REMOVAL  ###############################
#Append 'AutoScaleIgnore' tag with 'Patching' value to $tags list
$tags += @{AutoScaleIgnore="Patching"}

#Remove autoscaleignore tag
$a = $env:computername
$a = Get-AzVM -Name $a
Update-AZTag -Name $a.Name -ResourceGroupName $a.ResourceGroupName -Tag $tags -Operation Delete

######################################################################### 
0

There are 0 answers