PowerShell if和else脚本

时间:2017-05-10 08:04:39

标签: powershell

我正在编写一个脚本来启动虚拟机,如果它当前没有运行。我知道这样做的命令,但我的语法有问题。

在这个脚本中,我想选择一个虚拟机,如果它已经关闭,我的脚本就会启动它,但如果虚拟机处于启动状态,脚本会显示一条消息&#34;虚拟机正在运行&#34;。< / p>

此时我编写了一个脚本,但语法不正确:

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

1 个答案:

答案 0 :(得分:5)

您应该使用Where-Object cmdlet而不是Format-Table cmdlet来过滤正在运行的虚拟机。此外,您必须用大括号包装else语句:

if (Get-VM -name 'yourVmName' | Where-Object state -eq running) 
{
    write-host -foregroundcolor red "VM running"
}
else 
{
    start-vm -name 'yourVmName'
}