Skip to content

Instantly share code, notes, and snippets.

@torgro
Created November 4, 2016 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torgro/c7b9edc69b56c057ea4253bebfccb6e8 to your computer and use it in GitHub Desktop.
Save torgro/c7b9edc69b56c057ea4253bebfccb6e8 to your computer and use it in GitHub Desktop.
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