Reputation: 1
I am very new to Powershell and I am wanting to write a script that will check the status of Virtual Machines i.e running or stopped, then when the host machine reboots depending on the status of the VM's pior the the reboot it will start them or keep them in a stopped state.
So far I have written a script that will auto start all the local VM's on the host machine on start-up, however sometimes we shutdown a VM for a reason and don't want it starting back up again.
I have started writing a script that captures all the VM's on a host and writes it to a CSV file:
Get-VM | select VMName, State, Uptime| Export-CSV D:\VM.csv -NoTypeInformation
This produces the VMName and the current state ie "Running" or "Off"
My plan is to have this script run via a task scheduler every 12hrs and on-start up have a ps1 script run and grab the VMName and State and depending on the data Start the VM if it was previosuly running, or keep it in a stopped state if the value was set to "off"
Is there an easy way to write this?
Thanks.
Upvotes: 0
Views: 135
Reputation: 371
Maybe the following article is helpful to you: Using Task Scheduler for PowerShell
You can find the documentation of VM PowerShell CMDLET at VM PowerShell cmdlet
So for example if you have CSV file (vmstatus.csv) with VM Name and VM Status like:
VMNAME,VMstatus,
vm1,1
vm2,0
vm3,1
then maybe you can restart VM where the status is zero
$statusresult = Import-Csv -path C:\temp\vmstatus.csv
foreach ($st in $statusresult){
if ($St.VMSTATUS -eq 0){
Start-VM -Name $st.VMNAME
}
}
Upvotes: 0