Powershell 在不显示结果的情况下获取VM

Powershell 在不显示结果的情况下获取VM,powershell,hyper-v,Powershell,Hyper V,我想运行一个测试,看看hyper-v中是否已经存在VM 以下是我所拥有的: $VM = "DC" $VMName = Get-VM -name $VM if (!$VMname) { Write-Host "No VM named $VM exists" } else { Write-Host "A VM named $VM already exists" } 但是,如果VM不存在,它会抛出此错误 PS C:\Users\sowen> $VMName = Get-VM -name $V

我想运行一个测试,看看hyper-v中是否已经存在VM

以下是我所拥有的:

$VM = "DC"
$VMName = Get-VM -name $VM
if (!$VMname) { 
Write-Host "No VM named $VM exists" }
else
{ Write-Host "A VM named $VM already exists" }
但是,如果VM不存在,它会抛出此错误

PS C:\Users\sowen> $VMName = Get-VM -name $VM
Get-VM : A parameter is invalid. Hyper-V was unable to find a virtual machine with name DC.
At line:1 char:11
+ $VMName = Get-VM -name $VM
+           ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (DC:String) [Get-VM], VirtualizationInvalidArgumentException
    + FullyQualifiedErrorId : InvalidParameter,Microsoft.HyperV.PowerShell.Commands.GetVMCommand

                                                                                                          How could I silently find if a VM already exists on HyperV with powershell? 
根据Get VM支持公共参数。使用
-ErrorAction SilentlyContinue
可能是完成相同任务的更干净的方法

$VMName = Get-VM -name $VM -ErrorAction SilentlyContinue
或者仅仅是一次简单的尝试/捕捉也可以达到目的。我将使用上面的代码和一个简单的
If($VMName){}
来解释空返回

根据Get VM支持公共参数。使用
-ErrorAction SilentlyContinue
可能是完成相同任务的更干净的方法

$VMName = Get-VM -name $VM -ErrorAction SilentlyContinue
或者仅仅是一次简单的尝试/捕捉也可以达到目的。我将使用上面的代码和一个简单的
If($VMName){}
来解释空返回