如何在 powershell 中正确格式化该对象?

如何在 powershell 中正确格式化该对象?

我正在尝试创建一个包含所有驱动器信息的对象,如下所示:

[
  {"letter": "C:", "volumeName": "Disk C", "brand": "INTEL ModelName", "mediaType" : "Fixed hard disk media"},
  {"letter": "D:", "volumeName": "Disk D", "brand": "Seagate ModelName", "mediaType" : "Fixed hard disk media"},
]

但是以下 powershell 命令不仅会产生格式不良的结果,而且还会为第一个磁盘的每个属性创建一个对象,而不是将每个磁盘的所有属性放在一个对象中:

% {New-Object PSObject -Property @{'caption' =$(wmic logicaldisk get caption $_); 'volumeName' =$(wmic logicaldisk get VolumeName $_); 'brand' =$(wmic diskdrive get caption $_); 'format' =$(wmic diskdrive get mediaType $_);}} | format-list

更新

我尝试使用这个命令:

Get-WMIObject Win32_LogicalDisk | % {New-Object PSObject -Property @{'caption' =$($_.caption); 'volumeName' =$($_.VolumeName); 'brand' =$(); 'format' =$()}} | format-list

这给了我一半的价值

caption    : C:
brand      :
format     :
volumeName : SSD

caption    : D:
brand      :
format     :
volumeName : Disk D

caption    : E:
brand      :
format     :
volumeName : Disk e

caption    : F:
brand      :
format     :
volumeName :

答案1

以下是使用磁盘分区将磁盘与卷链接起来的实际示例。问题是卷并不直接链接到磁盘,而是通过分区链接

Get-WmiObject Win32_DiskDrive | 
Select-Object DeviceID, Model, MediaType |
ForEach-Object { 
    $o = $_
    Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition" |
    Select-Object @{ N='Model'; E={$o.Model} }, 
                  @{ N='MediaType'; E={$o.MediaType} }, 
                  DeviceID
} |
ForEach-Object {
    $o2 = $_
    Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition" |
    Select-Object @{ N='Letter'; E={$_.Name} }, 
                  VolumeName, 
                  @{ N='MediaType'; E={$o2.MediaType} }, 
                  @{ N='Model'; E={$o2.Model} }
}

相关内容