【问题标题】:Powershell and wmi, how to map logical disk/volumes to a hard disk or vice versa?Powershell和wmi,如何将逻辑磁盘/卷映射到硬盘,反之亦然?
【发布时间】:2011-06-16 21:24:19
【问题描述】:
Get-WmiObject -ComputerName $ip -Credential $credential -Class Win32_logicaldisk

这会得到我在“我的电脑”中看到的磁盘,例如。 C:, D:, E: 现在我如何获得相应的底层物理磁盘?

如果我运行以下命令

Get-WmiObject -ComputerName $ip -Credential $credential -Class win32_diskdrive

我得到磁盘 0、磁盘 1、磁盘 2

那么如何找出哪个逻辑磁盘在哪个物理磁盘上呢?

另一个问题是如何找出卷号?如果我运行 diskpart 并执行“list volume”,我会得到以下输出

  Volume ###  Ltr  Label        Fs     Type        Size     Status     Info
  ----------  ---  -----------  -----  ----------  -------  ---------  --------
  Volume 2     C                NTFS   Partition     59 GB  Healthy    Boot
  ...

如何知道逻辑盘 C: 是第 2 卷?

最好的问候,普里莫兹。

【问题讨论】:

  • 也许这会有所帮助:superuser.com/a/1618991/910769
  • 它不会在所有情况下都起作用,但是...如果卷没有驱动器号,请将其分配给它(Win32_volume.DriveLetter 属性是可写的),然后使用 Win32_LogicalDiskToPartition 或 Win32_DiskDriveToDiskPartition 和最后删除驱动器号。这只是一个建议,请勿在生产系统上测试此解决方案。

标签: powershell wmi disk


【解决方案1】:

试试这个

Get-WMIObject Win32_LogicalDisk | Foreach-Object {
    Get-WmiObject -Query "Associators of {Win32_LogicalDisk.DeviceID='$($_.DeviceID)'} WHERE ResultRole=Antecedent"
} | Format-Table

这为您提供了 WIn32_logicalDisk 的相关实例,其中 Win32_LogicalDisk 是关系中的依赖实体。因此,您获得了 Win32_DiskDrive 实例。

【讨论】:

  • 我没有获得 Win32_DiskDrive,我获得了 Win32_DiskPartition,但它让我走上了正确的轨道并“到达”了 DiskDrive。非常感谢!
【解决方案2】:

如果您不关心挂载点卷,其他关于 WMI 关系的答案很好,因为 WMI 无法直接将挂载点卷与分区或磁盘相关联。

但是有一个注册表项可以帮助您找出一些信息,这些信息将帮助您像 windows 那样建立连接:

function getVolumeInformation{
    param($hostName, $credential)
    $volumeInformation = getVolumeInformation -computerName $hostName -credential $credential                   


    $WMIRegistryMountedDeviceInfo = WMIRegistryMountedDeviceInfo -computerName $hostName -Credential $credential
    foreach($volumeSerial in $volumeInformation.keys){                        
        if($WMIRegistryMountedDeviceInfo.containsKey($volumeSerial)){                        
            $volumeInformation[$volumeSerial]["diskPartitionStartingOffset"]=$WMIRegistryMountedDeviceInfo[$volumeSerial].diskPartitionStartingOffset
            $volumeInformation[$volumeSerial]["diskDriveSignature"]=$WMIRegistryMountedDeviceInfo[$volumeSerial].diskDriveSignature
            $volumeInformation[$volumeSerial]["wmiValueRegistry"]=$WMIRegistryMountedDeviceInfo[$volumeSerial].wmiValue
        }   
    }
    return $volumeInformation
}



function getWMIVolumeInformation{
    param($computerName, $credential)
    $diskToVolumeAssociation = @{}
    $regexGetVolumeSerial = ".*Volume{(.*)}.*"
    $wmiVolumes = $null
    $wmiVolumes = Get-WmiObject Win32_Volume -Credential $credential -ComputerName $computerName -filter "DriveType != 5" -ErrorVariable errorWMIVolume -ErrorAction SilentlyContinue

    $volumeInfo = @{}

    $wmiVolumes |   Foreach-Object {
        $wmiVolume = $_
        if($wmiVolume.DeviceID -match  $regexGetVolumeSerial){
            $wmiVolumeSerial = $Matches[1]
            $volumeInfo[$wmiVolumeSerial] = @{}
            $volumeInfo[$wmiVolumeSerial]["wmiInfo"] = $wmiVolume
            $volumeInfo[$wmiVolumeSerial]["volumeDirectoryName"] = $wmiVolume.Name
            $volumeInfo[$wmiVolumeSerial]["label"] = $wmiVolume.label
            $volumeInfo[$wmiVolumeSerial]["serial"] = $wmiVolumeSerial
            $volumeInfo[$wmiVolumeSerial]["capacity"] = $wmiVolume.Capacity
            $volumeInfo[$wmiVolumeSerial]["freeSpace"] = $wmiVolume.FreeSpace
        }
    }
    return $volumeInfo  


}
function WMIRegistryMountedDeviceInfo{
    param($computerName, $mycreds)
    $MountPointRegistryInformation = @{}

    $hklm = 2147483650
    $registryKeyMountedDevices = "SYSTEM\MountedDevices"
    $regexMountPoint = ".*{(.*)}.*"

    $wmi = get-wmiobject -list "StdRegProv" -namespace root\default -computername $computerName -credential $mycreds
    $wmiMountedDeviceKey = ($wmi.EnumValues($hklm,$registryKeyMountedDevices))

    foreach($mountedDeviceRegistryName in $wmiMountedDeviceKey.sNames){

        if($mountedDeviceRegistryName -match $regexMountPoint){
            $wmiValue = ($wmi.GetBinaryValue($hklm,$registryKeyMountedDevices,$mountedDeviceRegistryName))
            if($wmiValue.uValue.Count -eq 12){
                $diskDriveSignature = [bitconverter]::ToUInt32($wmiValue.uValue[0..3],0)
                $diskPartitionStartingOffset = [bitconverter]::ToUInt64($wmiValue.uValue[4..11],0)
                $MountPointRegistryInformation[$Matches[1]]=@{"serial"=$Matches[1];
                    "mountedDeviceRegistryName"=$mountedDeviceRegistryName;
                    "diskDriveSignature"=$diskDriveSignature;
                    "diskPartitionStartingOffset"=$diskPartitionStartingOffset;
                    "wmiValue"=$wmiValue.uValue}

            }
        }      
    }

   return $MountPointRegistryInformation
}

此代码应该为每个签名返回一个哈希表,其中包含与 mountDevice 关联的磁盘的磁盘驱动器签名。它还返回 DiskPartitionStartingOffset,它将与与 mountDevice 关联的 partition.StartingOffset 相同。

如果您想自己编写代码,此注册表 SYSTEM\MountedDevices 值的前 4 个字节是磁盘驱动器签名,但要小心 little-endian。接下来的 8 个字节是 PartitionStartingOffset。

有了这些信息,您可以使用 WMI 获取磁盘驱动器信息并将所有内容组合在一起,以真正获取与您拥有的所有物理驱动器相关的所有卷,无论它们是如何安装的。

这不适用于跨区卷。

在此类注册表中玩游戏时要非常小心。

【讨论】:

  • 我正在尝试使用它,但格式似乎有点不对劲。顶部(function 上方)是否意味着是另一个脚本/函数的一部分,因为有一个 return 语句。
  • 你是对的。我编辑了我现在使用的代码的摘要。我不能全部说明,因为它是一个 900 行代码,旨在运行在运行各种 Windows 操作系统的远程计算机上。位转换器部分非常重要,因为以前的版本可能无法正确转换它。
【解决方案3】:

这里是 Chad Miller 的答案,修改后可与 PowerShell Core 一起使用,并带有适当的引号和撇号,因此它实际上可以在 Linux/Windows 上运行,并且无论术语设置如何(即,UTF-8 与否):

param ($ComputerName)

$partitions = Get-CimInstance -ComputerName $ComputerName Win32_DiskPartition

$partitions |
foreach `
{
  Get-CimInstance -ComputerName $ComputerName `
                  -Query "ASSOCIATORS OF `
                          {Win32_DiskPartition.DeviceID='$($_.DeviceID)'} `
                          WHERE AssocClass=Win32_LogicalDiskToPartition" |
  Add-Member -MemberType NoteProperty PartitionName $_.Name -PassThru |
  Add-Member -MemberType NoteProperty Block $_.BlockSize -PassThru |
  Add-Member -MemberType NoteProperty StartingOffset $_.StartingOffset -PassThru |
  Add-Member -MemberType NoteProperty StartSector ($_.StartingOffset/$_.BlockSize) `
             -PassThru
} |
Select SystemName, Name, PartitionName, Block, StartingOffset, StartSector |
Sort-Object -Property Name # Sort by Drive letter to improve quality of life
# Select code above starting to the left of the hash in this comment

【讨论】:

    【解决方案4】:

    这是我创建的完整脚本,用于列出逻辑磁盘、分区和分区偏移量,以检查磁盘对齐问题。 (来源:我的博客http://sev17.com/2009/02/disk-alignment-partitioning-the-good-the-bad-the-ok-and-the-not-so-ugly/)

    Param($Computer)
    $Partitions=Get-WmiObject -ComputerName $Computer -Namespace "root\cimv2" -Class "Win32_DiskPartition"
    $Partitions | ForEach-Object { Get-WmiObject -ComputerName $Computer -Namespace "root\cimv2" -Query “ASSOCIATORS OF {Win32_DiskPartition.DeviceID='$($_.DeviceID)'} WHERE AssocClass = Win32_LogicalDiskToPartition” |
    Add-Member -MemberType NoteProperty -Name "PartitionName" $_.Name |
    Add-Member -MemberType NoteProperty -Name "Block" $_.BlockSize |
    Add-Member -MemberType NoteProperty -Name "StartingOffset" $_.StartingOffset |
    Add-Member -MemberType NoteProperty -Name "StartSector" $($_.StartingOffset/$_.BlockSize) }
    $Partitions | Format-List *
    

    【讨论】:

    • 无法让它工作。 GWMI 在 Windows 2012 框中返回“无效的对象路径”,即使在没有 -computername 的情况下在本地运行。
    【解决方案5】:

    检查 Win32_LogicalDisktoPartition 这为您提供了逻辑磁盘到物理磁盘的映射以及该磁盘上的分区。仅获取每个磁盘驱动器的标签

     gwmi win32_volume | select name,label
    

    【讨论】:

      【解决方案6】:

      这里是使用内核的另一种选择。 Microsoft 建议不要这样做,但事实证明它非常有效地捕获跨区卷、挂载点和其他卷类型信息以帮助关联磁盘和卷。

       $scriptBlockInvokeCommandKernel32 = {
          param([array]$arrayOfVolumeSerial)
      
          $cSharpCodeKernel32GetDisk = @"
              using System;
              using Microsoft.Win32.SafeHandles;
              using System.IO;
              using System.Runtime.InteropServices;
      
      
              public class GetDisk
              {
                  private const uint IoctlVolumeGetVolumeDiskExtents = 0x560000;
                  private const uint HASMOREDATA = 234;
                  // 4 rounded to 8 + 8 + 8= 24
                  [StructLayout(LayoutKind.Sequential)]
                  public struct DiskExtent
                  {
                      public int DiskNumber;
                      public Int64 StartingOffset;
                      public Int64 ExtentLength;
                  }
      
                  //size 4 rounded to 8 + number of extends * 24
                  [StructLayout(LayoutKind.Sequential)]
                  public struct DiskExtents
                  {
                      public int numberOfExtents;
                      public DiskExtent extents;
                  }
                  //4
                  [StructLayout(LayoutKind.Sequential)]
                  public struct DiskExtentsBeforeArray
                  {
                      public int numberOfExtents;
                  }
      
                  [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
                  private static extern SafeFileHandle CreateFile(
                      string lpFileName,
                      [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess,
                      [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
                      IntPtr lpSecurityAttributes,
                      [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
                      [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes,
                      IntPtr hTemplateFile
                  );
      
                  [DllImport("Kernel32.dll", SetLastError = false, CharSet = CharSet.Auto)]
                  private static extern bool DeviceIoControl(
                      SafeFileHandle hDevice,
                      uint IoControlCode,
                      [MarshalAs(UnmanagedType.AsAny)] [In] object InBuffer,
                      uint nInBufferSize,
                      ref DiskExtents OutBuffer,
                      int nOutBufferSize,
                      ref uint pBytesReturned,
                      IntPtr Overlapped
                  );
      
                  [DllImport("Kernel32.dll", SetLastError = false, CharSet = CharSet.Auto)]
                  private static extern bool DeviceIoControl(
                      SafeFileHandle hDevice,
                      uint IoControlCode,
                      [MarshalAs(UnmanagedType.AsAny)] [In] object InBuffer,
                      uint nInBufferSize,
                      IntPtr outBuffer,
                      int nOutBufferSize,
                      ref uint pBytesReturned,
                      IntPtr Overlapped
                  );
      
      
                  [DllImport("Kernel32.dll", SetLastError = false, CharSet = CharSet.Auto)]
                  private static extern int GetLastError();
      
                  public static DiskExtent[] GetPhysicalDriveString(string path)
                  {
                      DiskExtent[] diskExtent = null;
                      path = path.TrimEnd('\\');
                      if (!path.StartsWith(@"\\.\"))
                          path = @"\\.\" + path;
      
                      SafeFileHandle safeFileHandle = CreateFile(path, FileAccess.Read, FileShare.Read | FileShare.Write, IntPtr.Zero, FileMode.Open, 0,
                      IntPtr.Zero);
                      if (safeFileHandle.IsInvalid)
                      {
                          Exception e = Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
                      }
      
                      uint bytesReturned = new uint();
                      DiskExtents VOLUME_DISK_EXTENTS = new DiskExtents();
                      bool result = DeviceIoControl(
                          safeFileHandle,
                          IoctlVolumeGetVolumeDiskExtents,
                          IntPtr.Zero,
                          0,
                          ref VOLUME_DISK_EXTENTS,
                          Marshal.SizeOf(VOLUME_DISK_EXTENTS),
                          ref bytesReturned,
                          IntPtr.Zero);
      
                      if (result)
                      {
                          diskExtent = new DiskExtent[1];
                          diskExtent[0] = VOLUME_DISK_EXTENTS.extents; 
                      }
                      else
                      {
                          int numberOfExtents = VOLUME_DISK_EXTENTS.numberOfExtents;
                          int lastError = GetLastError();
      
                          if (lastError == HASMOREDATA)
                          {
                              int size = 8 + 24 * numberOfExtents;
                              uint bytesReturned2 = new uint();
      
                              IntPtr blob = default(IntPtr);
                              blob = Marshal.AllocHGlobal(size);
                              bool resultMutipleDiskExtent = DeviceIoControl(
                                  safeFileHandle,
                                  IoctlVolumeGetVolumeDiskExtents,
                                  IntPtr.Zero,
                                  0,
                                  blob,
                                  (int)size,
                                  ref bytesReturned2,
                                  IntPtr.Zero
                              );
      
                              if (resultMutipleDiskExtent)
                              {
                                  DiskExtentsBeforeArray lie = default(DiskExtentsBeforeArray);
                                  lie = (DiskExtentsBeforeArray)Marshal.PtrToStructure(blob, typeof(DiskExtentsBeforeArray));
                                  diskExtent = new DiskExtent[lie.numberOfExtents];
                                  for (int i = 0; i <= lie.numberOfExtents - 1; i++)
                                  {
                                      IntPtr offset = new IntPtr(blob.ToInt64() + 8 + 24 * i);
                                      diskExtent[i] = (DiskExtent)Marshal.PtrToStructure(offset, typeof(DiskExtent));
                                  }
      
                              }
                          }
                          else{
                              throw new System.ComponentModel.Win32Exception();
                          }   
                      }
                      safeFileHandle.Close();
                      return diskExtent;
                  }
              } 
      "@
          $resultOfOperation =@{}
          $volumeKernelInfo =@{} 
          $type = Add-Type -TypeDefinition $cSharpCodeKernel32GetDisk -ErrorAction Continue -ErrorVariable errorAddType -PassThru
          if($errorAddType){
              $resultOfOperation["error"]= ("error at CsharpBuild" + $errorAddType)
          }
          foreach($volumeSerial in $arrayOfVolumeSerial){
              $volumeString = "Volume{" + $volumeSerial + "}"
              $volumeKernelInfo[$volumeSerial] = [GetDisk]::GetPhysicalDriveString($volumeString)
          }
          $resultOfOperation["volumeKernelInfo"]=$volumeKernelInfo
      
          return $resultOfOperation
      }
      

      你可以调用它:

      $resultVolumeMappingFromKernel = Invoke-Command -ScriptBlock $scriptBlockInvokeCommandKernel32 -ComputerName $hostName -Credential $credential -ArgumentList (,$arrayOfVolumeSerial)
      

      它需要在您想要使用管理员帐户的信息的远程机器上运行。

      【讨论】:

        猜你喜欢
        • 2015-01-19
        • 2021-11-10
        • 2011-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-24
        相关资源
        最近更新 更多