【问题标题】:Detect unmounted volumes on selected disk with PowerShell WMI or Diskpart使用 PowerShell WMI 或 Diskpart 检测选定磁盘上未安装的卷
【发布时间】:2012-01-22 01:50:47
【问题描述】:

如何将卸载的卷链接到物理磁盘?

假设我需要在磁盘 3 上查找并挂载未挂载的卷,编号为 DiskpartWMIC,或 PowerShell WMI。如何使用脚本找出未安装磁盘 3 的哪些卷?或者,给定的未安装卷(没有 DriveLetter)驻留在哪个物理磁盘上?

当一个卷被卸载时,它不存在逻辑磁盘或安装点。我想可以使用GetRelated 方法找到关系,但我找不到适合该任务的代码示例。

【问题讨论】:

    标签: windows-7 powershell command-line wmi-query wmic


    【解决方案1】:

    试试这个,它会:

    • 使用 WMI 获取给定驱动器索引 $targetDisk 的所有未挂载分区
    • 使用 diskpart 脚本将目标磁盘上发现的分区挂载到下一个可用驱动器号。

    使用GetRelated 方法就是知道您需要关联什么。它有助于了解 WMI 类代表您正在寻找的内容Win32_DiskPartition。在您的情况下,您希望找到与逻辑磁盘(未挂载)无关的分区,因此我们查找没有关联 Win32_LogicalDiskWin32_DiskPartition 实例。

    由于您只想在特定物理磁盘上卸载卷,我们需要进一步关联类。为此,我们需要获取 Win32_DiskPartition 的关联 Win32_DiskDrive 实例。

    $targetDisk = 3
    
    $unmounted = gwmi -class win32_DiskPartition | ? {
        ($_.GetRelated('Win32_LogicalDisk')).Count -eq 0 
    }
    
    if ($unmounted) {
        $commands = @()
        $unmounted | ? { $_.GetRelated('Win32_DiskDrive') | ? { $_.Index -eq $targetDisk} } | % {
            $commands += "select disk {0}" -f $_.DiskIndex
            $commands += "select partition {0}" -f ($_.Index + 1)
            $commands += "assign"
        }
    
        $tempFile = [io.path]::GetTempFileName()
        $commands | out-file $tempFile -Encoding ASCII
    
        $output = & diskpart.exe /s $tempFile 2>&1
        if ($LASTEXITCODE -ne 0) {
            Write-Error $output
        }
    }
    

    【讨论】:

    • 谢谢安迪!清晰且乐于助人。为什么您更喜欢使用 Diskpart 来挂载未挂载的卷?是否可以为此使用 WMI(如 Add Mount) - 如果可以,您能否给出脚本示例?
    • @sambul35 我在谷歌上搜索了一下怎么做,但没有找到我要找的东西,所以我选择了 diskpart。可能只是不会花一整天的时间寻找。
    • @sambul35 另外,我使用的是 XP,因此某些 WMI 类不可用,例如 Win32_Volume。
    【解决方案2】:

    将此代码集成到上述答案中:

    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    
    Set colItems = objWMIService.ExecQuery _
        ("Select * From Win32_Volume Where Name = 'D:\\'")
    
    For Each objItem in colItems
        objItem.AddMountPoint("W:\\Scripts\\")
    Next
    

    它在 Windows 7 PowerShell 中使用卷设备 ID 而不是其 DriveLetter,并将卷与磁盘 3 相关联,如上述答案所示。可以使用与上述类似的方法(AddMountPoint 或 Mount),但不使用 Diskpart。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2017-03-04
    • 2018-11-28
    • 2016-03-07
    相关资源
    最近更新 更多