Skip to content

Invoke-VMCommand

Azure: Invokes a power command for an Azure virtual machine

param(
	[Parameter(Mandatory = $true)]
	[string]$Name,

	[Parameter(Mandatory = $true)]
	[string]$ResourceGroupName,

	[Parameter(Mandatory = $true)]
	[ValidateSet('Stop', 'Start', 'Restart')]
	[string]$Command
)

try {
	Import-Module Az.Compute -ErrorAction Stop

	[hashtable]$cmdArgs = @{
		'ErrorAction'       = 'Stop'
		'Confirm'           = $false
		'Name'              = $Name
		'ResourceGroupName' = $ResourceGroupName
	}

	switch ($Command) {
		"Stop" {
			$cmdArgs.Add("Force", $true)
			$ret = Stop-AzVM @cmdArgs
		}
		"Start" {
			$ret = Start-AzVM @cmdArgs
		}
		"Restart" {
			$ret = Restart-AzVM @cmdArgs
		}
	}

	Write-Output $ret
} catch {
	Write-Error $_
	exit 1
}

The name of the virtual machine.

The name of the resource group containing the virtual machine.

The command to execute: Stop, Start, or Restart.

An interactive directory of PowerShell scripts.