Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
function Set-LabPowerstate
{
<#
.Synopsis
Sets powermode for VMs on XenServer
.DESCRIPTION
This can shutdown or restart a VM or a collection of VMs. The function supports WhatIf. The XenServerPSModule
and vaild credentials on the XenServer is required to run this function. This function supports pipelineinput
for the VMname parameter.
.EXAMPLE
PS> $SetLabPowerstate = @{
Credential = Get-Credential
XenServerUrl = "http://xenServer.domain.local"
VMname = "DC01"
}
PS> Set-LabPowerstate @SetLabPowerstate
This will startup the VM DC01.
.EXAMPLE
PS> $SetLabPowerstate = @{
Credential = Get-Credential
XenServerUrl = "http://xenServer.domain.local"
VMname = "DC01"
Shutdown = $true
}
PS> Set-LabPowerstate @SetLabPowerstate
This will shutdown the VM DC01.
.EXAMPLE
PS> $SetLabPowerstate = @{
Credential = Get-Credential
XenServerUrl = "http://xenServer.domain.local"
Shutdown = $true
}
PS> "DC01","DC02" | Set-LabPowerstate @SetLabPowerstate
This will shutdown the nodes DC01 and DC02 using the pipeline
#>
[cmdletbinding(
SupportsShouldProcess=$true,
ConfirmImpact='Medium')]
Param
(
[Parameter(Mandatory)]
[PScredential]
$Credential
,
[Parameter(Mandatory)]
[string]
$XenServerUrl
,
[Parameter(Mandatory, ValueFromPipeline)]
[string[]]
$VMname
,
[switch]
$Shutdown
)
Begin
{
$f = $MyInvocation.InvocationName
Write-Verbose -Message "$f - START"
Import-Module -Name XenServerPSModule -ErrorAction Stop
$ConnectXenServer = @{
url = $XenServerUrl
UserName = $Credential.GetNetworkCredential().UserName
Password = $Credential.GetNetworkCredential().Password
}
Write-Verbose -Message "$f - Connecting to XENserver $XenServerUrl"
Connect-XENserver @ConnectXenServer -ErrorAction Stop
}
Process
{
foreach($Name in $VMname)
{
$VM = Get-XenVM -Name $Name
if (-not $vm)
{
Write-Warning -Message "$f - VM with name [$Name] was not found"
continue
}
$output = [pscustomobject]@{
VMName = $Name
Action = "Shutdown"
}
if ($PSBoundParameters.ContainsKey("Shutdown"))
{
Write-Verbose -Message "$f - Scheduling Power off of VM '$Name'"
if ($PSCmdlet.ShouldProcess("$Name", "Shutting down"))
{
Invoke-XenVM -VM $VM -XenAction CleanShutdown -Async
$output
}
}
else
{
Write-Verbose -Message "Scheduling Power on of VM '$Name'"
if ($PSCmdlet.ShouldProcess("$Name", "Starting up"))
{
Invoke-XenVM -VM $VM -XenAction Start -Async
$output.Action = "StartUp"
$output
}
}
}
Write-Verbose -Message "$f - Disconnect from XENserver"
Disconnect-XenServer
}
End
{
Write-Verbose -Message "$f - END"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment