簡體   English   中英

Get-VM而不顯示結果

[英]Get-VM without showing results

我想運行測試以查看虛擬機是否已存在於hyper-v中

這是我所擁有的:

$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" }

但是,如果虛擬機不存在,則會引發此錯誤

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? 

根據TechNet, Get-VM支持通用參數。 使用-ErrorAction SilentlyContinue可能是完成同一件事的一種更干凈的方法

$VMName = Get-VM -name $VM -ErrorAction SilentlyContinue

或者只是簡單的try / catch也可以解決問題。 我只是將上面的代碼與一個簡單的If($VMName){}來說明空返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM