Azure VM Auto Start/Stop
前提条件
-
创建自动化账户
-
添加运行方式账户
-
在自动化账户添加runner(如如下脚本)
Param
(
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]
[String]
$AzSubscriptionId,
[Parameter(Mandatory=$false)]
[String]
$AzResourceGroup,
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]
[String]
$AzVMList="All",
[Parameter(Mandatory=$true)][ValidateSet("Start","Stop")]
[String]
$Action
)
$servicePrincipalConnection=Get-AutomationConnection -Name "AzureRunAsConnection"
"Logging in to Azure..."
Connect-AzAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
Select-AzSubscription -SubscriptionId $AzSubscriptionId
if ([String]::IsNullOrEmpty($AzResourceGroup))
{
if($AzVMList -ne "All")
{
$AzVMs = $AzVMList.Split(",")
[System.Collections.ArrayList]$AzVMsToHandle = $AzVMs
}
else
{
$AzVMs = (Get-AzVM).Name
[System.Collections.ArrayList]$AzVMsToHandle = $AzVMs
}
}
else
{
if($AzVMList -ne "All")
{
$AzVMs = $AzVMList.Split(",")
[System.Collections.ArrayList]$AzVMsToHandle = $AzVMs
}
else
{
$AzVMs = (Get-AzVM -ResourceGroupName $AzResourceGroup).Name
[System.Collections.ArrayList]$AzVMsToHandle = $AzVMs
}
}
foreach($AzVM in $AzVMsToHandle)
{
if(!(Get-AzVM | ? {$_.Name -eq $AzVM}))
{
throw " AzureVM : [$AzVM] - Does not exist! - Check your inputs "
}
}
if($Action -eq "Stop")
{
Write-Output "Stopping VMs";
foreach ($AzVM in $AzVMsToHandle)
{
$AzVMInfo = Get-AzVM -Name $AzVM -Status
$AzVMInfo_State = $AzVMInfo.PowerState
Write-Output "Azure VM: $AzVM , Status before $Action is $AzVMInfo_State"
}
foreach ($AzVM in $AzVMsToHandle)
{
Get-AzVM -Name $AzVM | Stop-AzVM -Force
}
Start-Sleep -Seconds 45
Write-Output "Waiting for latest power status"
foreach ($AzVM in $AzVMsToHandle)
{
$AzVMInfo = Get-AzVM -Name $AzVM -Status
$AzVMInfo_State = $AzVMInfo.PowerState
Write-Output "Azure VM: $AzVM , Status after $Action is $AzVMInfo_State"
}
}
else
{
Write-Output "Starting VMs";
foreach ($AzVM in $AzVMsToHandle)
{
$AzVMInfo = Get-AzVM -Name $AzVM -Status
$AzVMInfo_State = $AzVMInfo.PowerState
Write-Output "Azure VM: $AzVM , Status before $Action is $AzVMInfo_State"
}
foreach ($AzVM in $AzVMsToHandle)
{
Get-AzVM -Name $AzVM | Start-AzVM -NoWait
}
}
- 添加计划
本文来自博客园,作者:Jas0n0ss,转载请注明原文链接:https://www.cnblogs.com/Jas0n0ss/p/azure_auto_start_stop.html