Forum Discussion
Shutdown/Start VM from Hyper-v Cluster remotely with PS script
Hello, this is my first script that I manage to create from start to finish.
What it does it connects to a Hyper-V Cluster, looks for a specific VM in that cluster and retains the node that it resides on, then connects to the node to shutdown/start the VM.
I made it like this because using the specific cluster Hyper-V commands (Stop-ClusterResource) doesn't do a complete shutdown, it just puts the VM on a sleep/pause state.
If you have any advice on how to improve this I would be grateful.
# password saved in .txt
#(Get-Credential).Password | ConvertFrom-SecureString | Out-File -PSPath C:\Scripts\passCLU.txt
$path = "E:\Scripts\passCLU.txt"
$CLUIP = "--.22"
$LogID = "-"
$Node1IP = "--.20"
$Node2IP = "--.21"
$Node3IP = "--.24"
$Node4IP = "--.25"
$VM ="-" #couldn t pass this variable through invoke-command
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "--.22,--.20,--.21,--.24,--.25" -Force
#retrieves the password and creates the credentials
function InitPassword($path, $LogID) {
$global:password = Get-Content -Path $path | ConvertTo-SecureString
$global:cred = New-Object System.Management.Automation.PSCredential ($LogID, $global:password)
}
function Connect($NodeIP){
$global:session = New-PSSession -ComputerName $NodeIP -Credential $global:cred
}
InitPassword $path $LogID
Connect $CLUIP
#searches on the cluster for the node owner of the specific VM
$OwnerInf = Invoke-Command -Session $global:session -ScriptBlock {
$grClu = Get-ClusterGroup | where {$_.Name -eq "-" }
$OwnerNode = $grClu.OwnerNode
return $OwnerNode
}
Get-PSSession | Remove-PSSession
$NodeName=$OwnerInf.NodeName
if($NodeName -eq "NODE1"){
Connect $Node1IP}
if($NodeName -eq "NODE2"){
Connect $Node2IP}
if($NodeName -eq "NODE3"){
Connect $Node3IP}
if($NodeName -eq "NODE4"){
Connect $Node4IP}
if($args[0] -eq "stop"){
Invoke-Command -Session $global:session -ScriptBlock {Stop-VM -VMName "-" -force }}
else{
Invoke-Command -Session $global:session -ScriptBlock {Start-vm -VMName "-" }}
Get-PSSession | Remove-PSSession
- farismalaebSteel ContributorHi,
So what you are looking for is to completely shut down the VM, instead of placing it on hold? yes?