如何编写BAT脚本挂载/卸载本地G盘Google Drive中的VHDX文件?
解决VHDX挂载BAT脚本问题
问题根源
原脚本执行失败的核心原因是带空格的路径在BAT与PowerShell的参数传递中引号处理不规范,同时缺少卸载已挂载盘符的前置逻辑。
修正后的完整脚本
@echo off setlocal enabledelayedexpansion :: 配置VHDX路径和目标盘符 set "VHDX_FILE=G:\My Drive\o.vhdx" set "TARGET_LETTER=V" :: 卸载已挂载到V:的目标VHDX PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "&{ $targetVol = Get-Volume -DriveLetter '%TARGET_LETTER%' -ErrorAction SilentlyContinue if ($targetVol) { $attachedVhd = Get-DiskImage -ImagePath '%VHDX_FILE%' -ErrorAction SilentlyContinue if ($attachedVhd -and $attachedVhd.Attached) { Dismount-DiskImage -ImagePath '%VHDX_FILE%' -Confirm:$false echo 已卸载已挂载的%VHDX_FILE% } } }" :: 挂载VHDX并指定盘符为V: PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "&{ $mountResult = Mount-DiskImage -ImagePath '%VHDX_FILE%' -PassThru -ErrorAction Stop $mountResult | Get-Disk | Get-Partition | Get-Volume | Where-Object {!$_.DriveLetter} | Set-Volume -DriveLetter '%TARGET_LETTER%' echo 成功挂载%VHDX_FILE%到%TARGET_LETTER%: }" pause endlocal
关键细节说明
- 路径传递优化:通过BAT变量封装带空格的路径,避免直接写在PowerShell命令中引发的引号冲突。
- 卸载逻辑严谨性:先检查V:盘符是否存在,再验证该盘符对应的是目标VHDX,避免误卸载其他磁盘。
- 自动指定盘符:挂载后自动为未分配盘符的卷设置为V:,确保挂载结果符合预期。
- 权限要求:必须以管理员身份运行脚本,否则磁盘挂载/卸载命令会因权限不足失败。
内容的提问来源于stack exchange,提问作者CNC Cumberland
相关产品推荐
相关产品推荐

