如何跳过正在使用的VHD时自动复制VHD?

问题描述 投票:0回答:1

[我正在尝试复制一组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命令。

以上代码是否有问题,或者我是否完全无法完成此任务?

powershell robocopy vhd
1个回答
0
投票

未经测试,但我认为您的代码在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 
    }
}

希望有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.