我构建了一个脚本,该脚本使用Diskpart挂载(附加)VHD,清除一些系统文件,然后卸载(分离)它。它使用foreach循环,并假定使用相同的驱动器号清除多个VHD。但是,在第一个VHD之后,它将失败。我还注意到,当我尝试用diskpart手动附加VHD时,diskpart成功了,磁盘管理器显示了具有正确驱动器号的磁盘,但是在同一PoSH实例中,我无法连接(设置位置)到该驱动器。如果我在第一次打开PoSH时进行了手动diskpart,则可以附加和分离所有想要的文件,并且每次都获得驱动器号。我需要做些什么来重置脚本中的diskpart吗?这是我正在使用的脚本的片段。
function Mount-VHD {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[string]$Path,
[Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)]
[string]$DL,
[string]$DiskpartScript = "$env:SystemDrive\DiskpartScript.txt",
[switch]$Rescan
)
begin {
function InvokeDiskpart {
Diskpart.exe /s $DiskpartScript
}
## Validate Operating System Version ##
if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7 or Windows Server 2008 R2."}
}
process{
## Diskpart Script Content ## Here-String statement purposefully not indented ##
@"
$(if ($Rescan) {'Rescan'})
Select VDisk File="$Path" `nAttach VDisk
Exit
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
InvokeDiskpart
Start-Sleep -Seconds 3
@"
Select VDisk File="$Path"`nSelect partition 1 `nAssign Letter="$DL"
Exit
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
InvokeDiskpart
}
end {
Remove-Item -Path $DiskpartScript -Force ; ""
Write-Host "The VHD ""$Path"" has been successfully mounted." ; ""
}
}
function Dismount-VHD {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[string]$Path,
[switch]$Remove,
[switch]$NoConfirm,
[string]$DiskpartScript = "$env:SystemDrive\DiskpartScript.txt",
[switch]$Rescan
)
begin {
function InvokeDiskpart {
Diskpart.exe /s $DiskpartScript
}
function RemoveVHD {
switch ($NoConfirm) {
$false {
## Prompt for confirmation to delete the VHD file ##
"" ; Write-Warning "Are you sure you want to delete the file ""$Path""?"
$Prompt = Read-Host "Type ""YES"" to continue or anything else to break"
if ($Prompt -ceq 'YES') {
Remove-Item -Path $Path -Force
"" ; Write-Host "VHD ""$Path"" deleted!" ; ""
} else {
"" ; Write-Host "Script terminated without deleting the VHD file." ; ""
}
}
$true {
## Confirmation prompt suppressed ##
Remove-Item -Path $Path -Force
"" ; Write-Host "VHD ""$Path"" deleted!" ; ""
}
}
}
## Validate Operating System Version ##
if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7 or Windows Server 2008 R2."}
}
process{
## DiskPart Script Content ## Here-String statement purposefully not indented ##
@"
$(if ($Rescan) {'Rescan'})
Select VDisk File="$Path"`nDetach VDisk
Exit
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
InvokeDiskpart
Start-Sleep -Seconds 10
}
end {
if ($Remove) {RemoveVHD}
Remove-Item -Path $DiskpartScript -Force ; ""
}
}
三天,仍然没有答案。谁有想法?这对我拥有的项目造成了重大延迟
—
凯尔(Kyle)
您在什么操作系统上运行此脚本?我主要是因为8/2012具有内置的VHD安装/卸载cmdlet。您有一个检查要求7 / 2008R2,但没有最大值。
—
MikeBaz-MSFT 2012年