首页 > 解决方案 > 如何在 Powershell 中排除部分输出?

问题描述

我正在编写一个脚本,它接受设备 ID 作为参数来检查磁盘的使用百分比。这是我的代码。

$device_id = $args[0]

Get-WmiObject -Class Win32_LogicalDisk |
Select-Object -Property DeviceID,
@{label='UsedPercentage'; expression={[Math]::Round((($_.Size - $_.FreeSpace)/$_.Size) * 100, 2)}} | 
findstr $device_id

这是我的输出。我正在传递一个参数以按设备 ID 查看设备的使用情况。

PS D:\Development\Powershell> .\disk-usage.ps1 D:

D:                57.69

我想做的就是输出那个数字。我该怎么做呢?

标签: powershell

解决方案


无需用于findstr过滤输出。相反,使用参数参数来过滤您的 WMI 查询:

$device_id = $args[0]

# use argument to filter WMI query
Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID = '$device_id'" |ForEach-Object {
  # output the free space calculation, nothing else
  [Math]::Round((($_.Size - $_.FreeSpace)/$_.Size) * 100, 2)
}

推荐阅读