我正在尝试机器人复制一组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我的计划是使用尝试捕获来识别哪些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输出"object in use”错误。似乎尝试捕获被忽略了,而只运行Get-VHD命令。
上面的代码有什么问题吗?还是我完全没有意识到如何完成这一任务?
发布于 2020-04-25 11:05:13
未经测试,但我认为您的代码在try块中缺少-ErrorAction Stop。否则,成功的Get-VHD调用将输出Attached属性的值,即$true或$false。
此外,在catch块中,$_自动变量不再表示ForEach-Object循环中的项,而是表示正在抛出的异常。
尝试:
$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
}
}希望这有帮助
https://stackoverflow.com/questions/61424029
复制相似问题