Freigeben über


Deleting VM In Azure PowerShell Script

So the final one for today

a script to help you clean up after your messing :) and to help you keep the cost down.

Again usual disclaimers apply and use it as a framework to make it better!

Here you go!

 

function deleteVM($azurecloud,$vmname)
{
    Write-Host "Deleting VM(s) please wait...."
    if ($vmname -eq $null)
    {
        Get-AzureVM -ServiceName $azurecloud |Foreach-object {Remove-AzureVM -ServiceName $_.ServiceName -Name $_.Name -Force $true|out-null}
    }
    else
    {
        Remove-AzureVM -ServiceName $azurecloud -Name $vmname
    }
}

function stopvm($azurecloud,$vmname)
{
    write-host "Stopping VM Prior to deletion please wait.."
    if ($vmname -eq $null)
    {
        Get-AzureVM -ServiceName $azurecloud |Foreach-object {Stop-AzureVM -ServiceName $_.ServiceName -Name $_.Name -Force $true|out-null}
    }
    else
    {
        Stop-AzureVM -ServiceName $azurecloud -Name $vmname
    }
}

################################################################
# Please Change These Variables to Suit Your Environment
#
$azuresettings = "C:\Azure\azure.publishsettings"
$azurecloud = "PFESCDEMO"
#
################################################################

cls
Import-AzurePublishSettingsFile $azuresettings

write-host "Azure VM Deletion Script"
write-host "Options Menu:"
write-host "1.`t Delete One VM in a Cloud Service"
write-host "2.`t Delete ALL VM in a Cloud Service"
$answer = read-host "Please Select Your Choice"

Switch ($Answer)
{
    1{$vmname = read-host "Please Enter VM Name To Delete";StopVM $azurecloud $vmname;DeleteVM $azurecloud $vmname}
    2{$vmname = $null;read-host "THIS WILL DELETE ALL VM'S in Cloud Service:`t $azurecloud Press Enter To Continue";StopVM $azurecloud $vmname; DeleteVM $azurecloud $vmname}
}