Home > Blockchain >  How to exclude part of an output in Powershell?
How to exclude part of an output in Powershell?

Time:09-30

i am writing a script that accepts the device ID as an argument to check the used percentage of a disk. Here is my code.

$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

Here is my output. i am passing an argument to see usage of the device by device ID.

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

D:                57.69

What i want to do is to just output that number. How do i do this?

CodePudding user response:

There's no need to use findstr to filter the output. Instead, use the parameter argument to filter your WMI query:

$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)
}

CodePudding user response:

You can add the 'used percentage' as a property to the WMI object you get back from your query:

$deviceID = args[0]

$diskUsage = Get-WmiObject -Query "SELECT FreeSpace, Size FROM Win32_LogicalDisk WHERE DeviceID = '$deviceID'" |
    Add-Member -MemberType ScriptProperty -Name 'UsedPercentage' -Value {[Math]::Round((($this.Size - $this.FreeSpace)/$this.Size) * 100, 2)} -PassThru

Now, $diskUsage is a WMI object with Size, FreeSpace and UsedPercentage properties (as well as some WMI metadata properties you can ignore). You can output the value of any of them by refering to the one you want:

$diskUsage.UsedPercentage
15.3

Or show them in a neat table:

$diskUsage | Format-Table Size, FreeSpace, UsedPercentage -AutoSize

         Size    FreeSpace UsedPercentage
         ----    --------- --------------
1013310287872 858247196672           15.3
  • Related