Get-AzureRmSubscription | Where-Object {$_.SubscriptionId
-like "*499"}
| Select-AzureRmSubscription
#improvise the script per your need
#select your subscription or iterate through subscriptions if
desired
$action="stop"
#$action="start"
$excludeStartVMs = @("winweb1hdicp", "b", "c")
$includeStartVMs = @("MyWindowsVM", "e")
$excludeStopVMs = @("1", "2", "3")
$includeStopVMs = @("4", "5")
function Take-Action($vmname, $action) {
if ($action -eq "stop") {
return
Generic-Action $vmname
$excludeStopVMs,
$includeStopVMs
}
if ($action -eq "start") {
return
Generic-Action $vmname
$excludeStartVMs $includeStartVMs
}
return $true;
}
function Generic-Action($vmname, $excludeArray,
$includeArray) {
#iterate
through exclusion
foreach
($exclusionVM in
$excludeArray) {
if
($exclusionVM -eq
$vmname) {
return
$false
}
}
#iterate
through inclusion
foreach
($exclusionVM in
$includeArray) {
if
($exclusionVM -eq
$vmname) {
return
$true
}
}
#or else...
return $true;
}
#to handle situation where a vm is in weired situation, you
dont want to delete it to troubleshoot, but the operations kills your time
function Include-VM($vmname) {
foreach
($exclusionVM in
($excludeStartVMs +
$excludeStopVMs)) {
if
($exclusionVM -eq
$vmname) {
return
$false
}
}
return $true
}
#select your subscription or iterate through subscriptions if
desired
$sw = [Diagnostics.Stopwatch]::StartNew()
foreach ($rg
in Get-AzureRmResourceGroup)
{
foreach($vm in Get-AzureRmVM -ResourceGroupName
$rg.ResourceGroupName){
Write-Host
$rg.ResourceGroupName $vm.Name
if
(Include-VM $vm.Name) {
#get
status
$status
= ((Get-AzureRmVM
-ResourceGroupName $rg.ResourceGroupName -Name
$vm.Name
-Status).Statuses).DisplayStatus
Write-Host
$status
if
($action -eq
"stop") {
if
($status -like
("*running*")) {
if
(Take-Action $vm.Name $action)
{
Write-Host "Going to stop
..." $rg.ResourceGroupName $vm.Name
Stop-AzureRmVM -ResourceGroupName $rg.ResourceGroupName
-Name $vm.Name
#doesnt prompt for confirmation...(for non-interactive/batch mode)
#Stop-AzureRmVM -ResourceGroupName -Force $rg.ResourceGroupName
-Name $vm.Name
Write-Host "Stopped:"
$rg.ResourceGroupName
$vm.Name
}
}
}#end
of stop action
if
($action -eq
"start") {
if
($status -like
("*Stopped*") -or $status -like ("*deallocated*"))
{
if
(Take-Action $vm.Name $action)
{
Write-Host
"Going to start ..." $rg.ResourceGroupName
$vm.Name
$confirmStatus=Read-Host 'Are you sure
you want to start the VM Yes(1)/No(2) followed by <Enter> [default
No(2)]'
if ($confirmStatus -eq $null -or $confirmStatus.Length -eq 0) {
$confirmStatus="2"
}
if ($confirmStatus -eq "1")
{
Start-AzureRmVM -ResourceGroupName
$rg.ResourceGroupName
-Name $vm.Name
Write-Host "Started:"
$rg.ResourceGroupName
$vm.Name
}
}
}
}#end
of start
} #end of
include vm
}
}
$sw.Stop()
$sw.Elapsed
No comments:
Post a Comment