1

I am writing a script to start a VM if it's not currently running. I know the commands to do that, but I got trouble with the syntax.

In this script I want to select a virtual machine and if it is off, my script just starts it, but if the VM is on, the script displays a message "The VM is running".

At this time I write a script but the syntax is not correct:

if (Get-VM | Format-Table name, state -eq running) {
    Write-Host -ForegroundColor red "VM running
}
else(start-vm -name "name")

1 Answer 1

5

You should use the Where-Object cmdlet instead of the Format-Table cmdlet to filter the vms that is running. Also, you have to wrap your else statement with curly brackets:

if (Get-VM -name 'yourVmName' | Where-Object state -eq running) 
{
    write-host -foregroundcolor red "VM running"
}
else 
{
    start-vm -name 'yourVmName'
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.