如何在PowerShell中正确格式化此对象?

时间:2018-05-29 10:49:27

标签: windows shell powershell command-line command-line-interface

我正在尝试创建一个对象,其中包含有关所有看起来像这样的驱动器的信息:

[
  {"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

1 个答案:

答案 0 :(得分:2)

您可以直接使用Get-WmiObject win32_logicaldisk而不是使用wmic:

来获取它
Get-WmiObject win32_logicaldisk | select `
@{N="letter";E={$_.deviceId}},
@{N="volumeName";E={$_.VolumeName}},
@{N="brand";E={$_.deviceId}},
@{N="mediaType";E={$_.Description}}

<强>结果:

letter volumeName brand mediaType              
------ ---------- ----- ---------              
A:                A:    3 1/2 Inch Floppy Drive
C:                C:    Local Fixed Disk       
D:     OST        D:    Local Fixed Disk       
K:     DATA       K:    CD-ROM Disc