首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在机器人复制VHD的同时跳过正在使用的VHD?

如何在机器人复制VHD的同时跳过正在使用的VHD?
EN

Stack Overflow用户
提问于 2020-04-25 10:08:40
回答 1查看 196关注 0票数 0

我正在尝试机器人复制一组VHD,同时跳过正在使用的VHD。

为此,我试图创建一个清单,列出所有未使用的VHD。如果没有使用VHD,我将能够运行Get-VHD并检查.Attached属性是否为false。如果VHD正在使用,我会得到以下错误:

代码语言:javascript
复制
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

我的计划是使用尝试捕获来识别哪些VHD正在使用,创建一个文件名列表,然后将其传递给robocopy /xf选项。为此,以下代码应该输出所有正在使用的VHD的名称以供控制台使用:

代码语言:javascript
复制
$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输出"object in use”错误。似乎尝试捕获被忽略了,而只运行Get-VHD命令。

上面的代码有什么问题吗?还是我完全没有意识到如何完成这一任务?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-25 11:05:13

未经测试,但我认为您的代码在try块中缺少-ErrorAction Stop。否则,成功的Get-VHD调用将输出Attached属性的值,即$true$false

此外,在catch块中,$_自动变量不再表示ForEach-Object循环中的项,而是表示正在抛出的异常

尝试:

代码语言:javascript
复制
$VHDLocation = "\\server\share"
$VHDs = Get-Children -Path $VHDLocation -Include "*.vhd" -Recurse

# try and get an array of unattached VHD full file names
$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)) { $vhd.FullName }
    }
    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.FullName
    }
}

希望这有帮助

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61424029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档