Here is the PowerShell runbook script which can be scheduled in Azure.
This is more stable, simpler and easier to manage.
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID `
-ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
Write-Output "Connection established."
$vmname = 'AZ532-test1'
$VMDetail = Get-AzureRMVM -ResourceGroupName $ResourceGroupName -Name $VmName -Status
$vmPowerstate = $VMDetail[1].Code
Write-Verbose "vmPowerstate: $vmPowerstate"
if ($vmPowerstate -like "PowerState/running"){
write-host "VM '$vmname' is ""$vmPowerstate"". Skip."
}
else{
write-host "Starting VM '$vmname'"
Start-AzureRMVM -ResourceGroupName $ResourceGroupName -Name $VmName -Verbose
}
# if ($vmPowerstate -like "PowerState/running"){
# write-host "Stopping VM '$vmname'"
# Stop-AzureRMVM -ResourceGroupName $ResourceGroupName -Name $VmName -Verbose -Force
# }
# else{
# write-host "VM '$vmname' is ""$vmPowerstate"". Skip."
# }
==============
Azure classic VM is similar:
$ConnectionAssetName = "AzureClassicRunAsConnection"
$connection = Get-AutomationConnection -Name $connectionAssetName
Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
if ($Conn -eq $null)
{
throw "Could not retrieve connection asset: $ConnectionAssetName. Assure that this asset exists in the Automation account."
}
Write-Output "Connection established."
$CertificateAssetName = $Conn.CertificateAssetName
Write-Verbose "Getting the certificate: $CertificateAssetName" -Verbose
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
if ($AzureCert -eq $null)
{
throw "Could not retrieve certificate asset: $CertificateAssetName. Assure that this asset exists in the Automation account."
}
Write-Verbose "Authenticating to Azure with certificate." -Verbose
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
$vmname = 'hvEF4'
$vm = Get-AzureVM | Where-Object { $_.Name -eq $vmname }
write-host "AzureVM: "
$vm | fl *
# if ($vm.PowerState -eq "Started"){
# write-host "Stopping VM '$vmname'"
# $vm | Stop-AzureVM -Force
# }
# else{
# write-host "VM '$vmname' is ""$($vm.PowerState)"". Skip."
# }
if ($vm.PowerState -eq "Started"){
write-host "VM '$vmname' is ""$($vm.PowerState)"". Skip."
}
else{
write-host "Starting VM '$vmname'"
$vm | Start-AzureVM
}
write-host "done."
No comments:
Post a Comment