Luca9698
Luca9698

Reputation: 31

PowerShell if and else scripts

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")

Upvotes: 1

Views: 414

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

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'
}

Upvotes: 5

Related Questions