[我正在尝试复制一组VHD,同时跳过正在使用的VHD。
为此,我正在尝试创建所有未使用的VHD的列表。如果未使用VHD,则可以运行Get-VHD
并检查.Attached
属性是否为false。如果正在使用VHD,则会出现以下错误:
Get-VHD Getting the mounted storage instance for the path <VHD-Path> failed.
The operation cannot be performed while the object is in use.
CategoryInfo: ResourceBusy: (:) [Get-VHD], VirtualizationException
FullyQualifiedErrorID: ObjectInUse,Microsoft.Vhd.PowerShell.Cmdlets.GetVHD
我的计划是使用try-catch识别正在使用的VHD,创建其文件名列表,然后将其传递给robocopy /xf
选项。为此,以下代码应将所有使用中的VHD的名称输出到控制台:
$VHDLocation = "\\server\share"
$VHDs = Get-Children -Path $VHDLocation -Include "*.vhd" -Recurse
$VHDs | ForEach-Object {
try { Get-VHD ($VHDLocation + "\" + $_)).Attached }
catch { Write-Output $_ }}
但是,当我运行它时,Powershell为未使用的VHD输出“ False”,而为正在使用的VHD输出“正在使用对象”错误。似乎try-catch被忽略了,而只运行了Get-VHD
命令。
以上代码是否有问题,或者我是否完全无法完成此任务?
未经测试,但我认为您的代码在try块中缺少-ErrorAction Stop
。否则,成功的Get-VHD
调用将输出Attached
属性的值,即$true
或$false
。同样,一旦进入catch块,$_
自动变量将不再表示ForEach-Object循环中的项目,而是表示exception被抛出。
尝试:
$VHDLocation = "\\server\share"
$VHDs = Get-Children -Path $VHDLocation -Include "*.vhd" -Recurse
# try and get an array of unattached VHD objects
$unAttached = foreach($vhd in $VHDs) {
try {
# ErrorAction Stop ensures exceptions are being handled in the catch block
$disk = $vhd | Get-VHD -ErrorAction Stop
# if you get here, the Get-VHD succeeded, output if Attached is False
if (!($disk.Attached)) { $disk }
}
catch {
# exception is thrown, so VHD must be in use; output this VHD object
# inside a catch block, the '$_' automatic variable represents the exception
$vhd
}
}
希望有所帮助