【发布时间】:2020-11-22 22:52:51
【问题描述】:
这是关于Combine `Get-Disk` info and `LogicalDisk` info in PowerShell?的答案的问题
这是我尝试更改的答案,以按照我想要的方式格式化输出: https://stackoverflow.com/a/31092004/8262102
它需要像下面的代码一样仅以所需的格式适用于多个驱动器。
这是包含我尝试这样做的所有详细信息的代码:
$info_diskdrive_basic = Get-WmiObject Win32_DiskDrive | ForEach-Object {
$disk = $_
$partitions = "ASSOCIATORS OF " + "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " + "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
Get-WmiObject -Query $partitions | ForEach-Object {
$partition = $_
$drives = "ASSOCIATORS OF " + "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " + "WHERE AssocClass = Win32_LogicalDiskToPartition"
Get-WmiObject -Query $drives | ForEach-Object {
[PSCustomObject][Ordered]@{
Disk = $disk.DeviceID
DiskModel = $disk.Model
Partition = $partition.Name
RawSize = '{0:d} GB' -f [int]($partition.Size/1GB)
DriveLetter = $_.DeviceID
VolumeName = $_.VolumeName
Size = '{0:d} GB' -f [int]($_.Size/1GB)
FreeSpace = '{0:d} GB' -f [int]($_.FreeSpace/1GB)
}
}
}
}
# Here's my attempt at formatting the output of the code above.
# 1. This trims the dead whitespace from the output.
$info_diskdrive_basic = ($info_diskdrive_basic | Out-String) -replace '^\s+|\s+$', ('')
# 2. I then separate the DiskModel, RawSize, DriveLetter, VolumeName, FreeSpace with the regexp below so this becomes:
# Disk Model, Raw Size, Drive Letter, Volume Name, Free Space
$info_diskdrive_basic = ($info_diskdrive_basic) -replace '(?-i)(?=\B[A-Z][a-z])', (' ')
# 3. Here I then format the string to how I want:
$info_diskdrive_basic = ($info_diskdrive_basic) -replace '(.+?)(\s+):\s*(?!\S)', ($id2 + '$1:$2 ')
$info_diskdrive_basic
输出应如下所示:
我想像这样格式化属性和值:Properties: >spaces< value,其中值在右侧并沿它们的左侧对齐
# Disk: \\.\PHYSICALDRIVE0
# Disk Model: Crucial_CT512MX100SSD1
# Partition: Disk #0, Partition #2
# Raw Size: 476 GB
# Drive Letter: C:
# Volume Name:
# Size: 476 GB
# Free Space: 306 GB
但我的输出最终是这样的:(注意文本未对齐)
# Disk: \\.\PHYSICALDRIVE0
# Disk Model: Crucial_CT512MX100SSD1
# Partition: Disk #0, Partition #2
# Raw Size: 476 GB
# Drive Letter: C:
# Volume Name:
# Size: 476 GB
# Free Space: 306 GB
【问题讨论】:
-
为什么不直接输出
$info_diskdrive_basic | Format-List而不是执行这些步骤1、2和3? -
我还有很多其他代码可以输出系统信息,这些代码使用
Description: Value遵循这种格式,所以我想用同样的方式。 -
所以基本上,您想要
Format-List产生的输出,但是在属性名称和实际值之间有很多额外的空格?再次:为什么? -
我给出了原因,所有其他输出都是这样的,它根据示例将右侧的属性与左对齐对齐。