Jump to page sections
- Running it natively on Linux for the sake of getting PowerShell objects in pwsh
- Getting the disk space report from Windows
- A single target computer
- Parsing the Linux utility df's output
- Multiple target computers
- Random example
Original date of publishing: Likely sometime in 2016-2018. Last edit: 2024-09-13. (Added better support for using it natively on Linux).
Running it natively on Linux for the sake of getting PowerShell objects in pwsh
Here's a demo of running it natively on Linux, and of the clumsily named parameter "-Add1024DividedDiskSizeProperties".
PS /> ConvertFrom-LinuxDfOutput -Text (df --portability) | Format-Table -AutoSize Filesystem 1024-blocks Used Available CapacityUsedPercent MountedOn ---------- ----------- ---- --------- ------------------- --------- tmpfs 596488.000 5332.000 591156.000 1.000 /run /dev/nvme0n1p4 60159876.000 49618948.000 7452544.000 87.000 / tmpfs 2982432.000 29484.000 2952948.000 1.000 /dev/shm tmpfs 5120.000 12.000 5108.000 1.000 /run/lock efivarfs 128.000 48.000 76.000 39.000 /sys/firmware/efi/efivars /dev/nvme0n1p1 98304.000 75764.000 22540.000 78.000 /boot/efi tmpfs 596484.000 2588.000 593896.000 1.000 /run/user/1000PS /> ConvertFrom-LinuxDfOutput -Text (df --portability) -Add1024DividedDiskSizeProperties | Select-Object -First 2
Filesystem : tmpfs 1024-blocks : 596488 Used : 5332 Available : 591156 CapacityUsedPercent : 1 MountedOn : /run 1024-blocksMB : 5.20703125 1024-blocksGB : 0.005084991455078125 MBUsed : 5.20703125 GBUsed : 0.005084991455078125 MBAvailable : 577.30078125 GBAvailable : 0.563770294189453125 Filesystem : /dev/nvme0n1p4 1024-blocks : 60159876 Used : 49619000 Available : 7452492 CapacityUsedPercent : 87 MountedOn : / 1024-blocksMB : 48456.0546875 1024-blocksGB : 47.32036590576171875 MBUsed : 48456.0546875 GBUsed : 47.32036590576171875 MBAvailable : 7277.82421875 GBAvailable : 7.107250213623046875PS /> $DiskReportObjects = ConvertFrom-LinuxDfOutput -Text (df --portability) -Add1024DividedDiskSizeProperties
PS /> $DiskReportObjects.Where({$_.Filesystem -eq 'tmpfs'}) | Select-Object -First 1 | ForEach-Object { if ($_.AvailableMB -lt 800) { 'Low disk space...' } } Low disk space... PS /> $DiskReportObjects.Where({$_.Filesystem -eq 'tmpfs'}) | Select-Object -First 1 | ForEach-Object { if ($_.AvailableMB -lt 800) { 'Low disk space...' }; $_ } Low disk space... Filesystem : tmpfs 1024-blocks : 596488 Used : 5332 Available : 591156 CapacityUsedPercent : 1 MountedOn : /run 1024-blocksMB : 5.20703125 1024-blocksGB : 0.005084991455078125 MBUsed : 5.20703125 GBUsed : 0.005084991455078125 MBAvailable : 577.30078125 GBAvailable : 0.563770294189453125 PS />
Getting the disk space report from Windows
I use my own SSH from PowerShell module to execute the command "df --portability" on the remote Linux hosts to retrieve disk usage data, and then parse the results using a couple of regular expressions, to produce standardized and sortable custom PowerShell objects with numerical and string types.
The code is provided under the MIT license.
NB! This code shows the behavior of the "old" module. In the new version 2 fork you will do it slightly differently (surround the expression in parentheses and index into the "Result" property to get the text to parse). I currently don't have the energy to update, plus this is useful for people using the old module, so for now I'm just adding this information here at the top.
I'll demonstrate how you can use it in an acceptable way.
The code in this article is written to be compatible with use from PowerShell version 2 and up. PowerShell v2 comes built in with Windows 7 and Windows Server 2008 R2 (and is available for XP/2003 R2).
This screenshot sums it up pretty well.

A single target computer
Connect to the remote Linux hosts using New-SshSession from the SSH-Sessions module there's a link to above.
Here I connect to the computer ubuntuvm. I already had a session to the IP you see in the output from Get-SshSession.
PS C:\Dropbox\PowerShell> New-SshSession -Comp ubuntuvm -User joakimbs # prompted for password in ISE Successfully connected to ubuntuvmPS C:\Dropbox\PowerShell> Get-SshSession | Format-Table -AutoSize
ComputerName Connected ------------ --------- 192.168.1.77 True ubuntuvm True
Then I just get the output from the Linux command "df --portability". The --portability parameter makes it a bit easier to parse programmatically. Only tested against Ubuntu 14.04 and Centos6, but this should be fairly consistent across GNU+Linux - I think.
PS C:\PS> $dfoutput = Invoke-SshCommand -Comp ubuntuvm -Command 'df --portability' -Quiet PS C:\PS> $dfoutput[0] Filesystem 1024-blocks Used Available Capacity Mounted on udev 1014160 4 1014156 1% /dev tmpfs 204992 1332 203660 1% /run /dev/sda1 23606716 7834904 14549620 36% / none 4 0 4 0% /sys/fs/cgroup none 5120 0 5120 0% /run/lock none 1024960 144 1024816 1% /run/shm none 102400 32 102368 1% /run/user
That's fine for manual, visual inspection, but if we would like to generate reports or something to trigger on a condition like "above 90 % use should generate a warning", or whatever, we will need to parse the results into objects with the disk sizes and percentages turned into numerical properties.
Understanding the data structure we get from Invoke-SshCommand can be a bit less than intuitive, but it's really an array of single strings that contain newlines. If you write the $dfoutput to file with something like:
$dfoutput[0] | Set-Content Linux-disk-usage.txt
It will be turned into several lines in the file, so if you're parsing data from files, you will need to join them into one long, newline-separated string, for instance like this:
$MyDfOutput = (Get-Content Linux-disk-usage.txt) -join "`n"
With PowerShell version 3 and up you can use the -Raw parameter for Get-Content, like this:
$DfOutput = Get-Content -Raw -LiteralPath Linux-disk-usage.txt
Parsing the Linux utility df's output
So here comes the magical part that turns the df output into custom PowerShell objects. I wrote a ConvertFrom-LinuxDfOutput function that takes a multiline, single string as input (as produced from SSH-Sessions).
Here's the code to store in a file called "ConvertFrom-LinuxDfOutput.ps1":
#requires -version 2
function ConvertFrom-LinuxDfOutput {
<#
.SYNOPSIS
Convert output from the Linux utility 'df' with the parameter '--portability'
into PowerShell objects with numerical types. Optionally add MB and GB properties
using the '-Add1024DividedDiskDizeProperties' parameter.
Author: Joakim Borger Svendsen, Svendsen Tech. 2024-09-13.
MIT License.
#>
[CmdletBinding()]
param(
[String[]] $Text,
[Switch] $Add1024DividedDiskSizeProperties
)
# Add this in an attempt to support direct output from 'df --portability' natively on Linux.
$Text = $Text -split '(?:\r?\n)+' -join "`n"
[regex] $HeaderRegex = '\s*File\s*system\s+1024-blocks\s+Used\s+Available\s+Capacity\s+Mounted\s*on\s*'
[regex] $LineRegex = '^\s*(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\s*%)\s+(.+)\s*$'
$Lines = @($Text -split '(?:\r?\n)+')
Write-Verbose "Line count: $($Lines.Count)"
if ($Lines[0] -match $HeaderRegex) {
$FileSystemObjects = @(foreach ($Line in ($Lines | Select-Object -Skip 1)) {
[regex]::Matches($Line, $LineRegex) | ForEach-Object {
New-Object -TypeName PSObject -Property @{
Filesystem = $_.Groups[1].Value
'1024-blocks' = [Decimal] $_.Groups[2].Value
Used = [Decimal] $_.Groups[3].Value
Available = [Decimal] $_.Groups[4].Value
CapacityUsedPercent = [Decimal] ($_.Groups[5].Value -replace '\D')
MountedOn = $_.Groups[6].Value
} | Select-Object Filesystem, 1024-blocks, Used, Available, CapacityUsedPercent, MountedOn
}
})
}
else {
Write-Warning -Message "Error in input. Failed to recognize headers from 'df --portability' output."
# Exit the function.
return
}
if ($Add1024DividedDiskSizeProperties) {
foreach ($FileSystemObject in $FileSystemObjects) {
Add-Member -InputObject $FileSystemObject -MemberType NoteProperty -Name '1024-blocksMB' -Value ($FileSystemObject.Used / (1024))
Add-Member -InputObject $FileSystemObject -MemberType NoteProperty -Name '1024-blocksGB' -Value ($FileSystemObject.Used / (1024*1024))
Add-Member -InputObject $FileSystemObject -MemberType NoteProperty -Name MBUsed -Value ($FileSystemObject.Used / (1024))
Add-Member -InputObject $FileSystemObject -MemberType NoteProperty -Name GBUsed -Value ($FileSystemObject.Used / (1024*1024))
Add-Member -InputObject $FileSystemObject -MemberType NoteProperty -Name MBAvailable -Value ($FileSystemObject.Available / (1024))
Add-Member -InputObject $FileSystemObject -MemberType NoteProperty -Name GBAvailable -Value ($FileSystemObject.Available / (1024*1024))
}
}
# Explicitly return the objects.
return $FileSystemObjects
}
You can download it here: ConvertFrom-LinuxDfOutput.ps1.txt. Right-click, save as, rename to .ps1, unblock and dot-source.
I also updated/put it on GitHub here: https://github.com/EliteLoser/misc/blob/master/PowerShell/ConvertFrom-LinuxDfOutput.ps1
And it works like this:
PS C:\PS> . .\ConvertFrom-LinuxDfOutput.ps1 # dot-sourcing PS C:\PS> ConvertFrom-LinuxDfOutput -Text $dfoutput[0] | ft -a Filesystem 1024-blocks Used Available CapacityPercent MountedOn ---------- ----------- ---- --------- --------------- --------- udev 1014160 4 1014156 1 /dev tmpfs 204992 1332 203660 1 /run /dev/sda1 23606716 7834904 14549620 36 / none 4 0 4 0 /sys/fs/cgroup none 5120 0 5120 0 /run/lock none 1024960 144 1024816 1 /run/shm none 102400 32 102368 1 /run/user
Multiple target computers
And now back to the beginning where we processed all the computers we have a connection to, as provided from Get-SshSession.
This can be done as follows.
PS C:\Dropbox\PowerShell> Get-SshSession | Select -Exp ComputerName |
%{ $c = $_; ConvertFrom-LinuxDfOutput -Text (Invoke-SshCommand -Comp $_ -Command 'df --portability' -q) } |
Select @{n='ComputerName';e={$c}}, * | ft -AutoSize
ComputerName Filesystem 1024-blocks Used Available CapacityPercent MountedOn
------------ ---------- ----------- ---- --------- --------------- ---------
192.168.1.77 /dev/mapper/VolGroup-lv_root 51475068 3675556 45178072 8 /
192.168.1.77 tmpfs 961124 0 961124 0 /dev/shm
192.168.1.77 /dev/sda1 487652 153394 308658 34 /boot
192.168.1.77 /dev/mapper/VolGroup-lv_home 70608288 53072 66961796 1 /home
ubuntuvm udev 1014160 4 1014156 1 /dev
ubuntuvm tmpfs 204992 1332 203660 1 /run
ubuntuvm /dev/sda1 23606716 7834904 14549620 36 /
ubuntuvm none 4 0 4 0 /sys/fs/cgroup
ubuntuvm none 5120 0 5120 0 /run/lock
ubuntuvm none 1024960 144 1024816 1 /run/shm
ubuntuvm none 102400 32 102368 1 /run/user
Testing has been limited.
Random example
PS C:\PS> $temp = Get-SshSession | Select -Exp ComputerName |
%{ $c = $_; ConvertFrom-LinuxDfOutput -Text (Invoke-SshCommand -Comp $_ -Command 'df --portability' -q) } |
Select @{n='ComputerName';e={$c}}, *
PS C:\PS> $temp.Count
11
PS C:\PS> $temp | ft -A
ComputerName Filesystem 1024-blocks Used Available CapacityPercent MountedOn
------------ ---------- ----------- ---- --------- --------------- ---------
192.168.1.77 /dev/mapper/VolGroup-lv_root 51475068 3675588 45178040 8 /
192.168.1.77 tmpfs 961124 0 961124 0 /dev/shm
192.168.1.77 /dev/sda1 487652 153394 308658 34 /boot
192.168.1.77 /dev/mapper/VolGroup-lv_home 70608288 53072 66961796 1 /home
ubuntuvm udev 1014160 4 1014156 1 /dev
ubuntuvm tmpfs 204992 1332 203660 1 /run
ubuntuvm /dev/sda1 23606716 7834916 14549608 36 /
ubuntuvm none 4 0 4 0 /sys/fs/cgroup
ubuntuvm none 5120 0 5120 0 /run/lock
ubuntuvm none 1024960 144 1024816 1 /run/shm
ubuntuvm none 102400 32 102368 1 /run/user
PS C:\PS> $temp | Where { $_.Filesystem -eq 'tmpfs' } |
sort -Descending available | ft -AutoSize
ComputerName Filesystem 1024-blocks Used Available CapacityPercent MountedOn
------------ ---------- ----------- ---- --------- --------------- ---------
192.168.1.77 tmpfs 961124 0 961124 0 /dev/shm
ubuntuvm tmpfs 204992 1332 203660 1 /run
Powershell
Windows
Linux
Regex
SSH
Blog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How Many Bitcoins (BTC) Are Lost
- How many people own 1 full BTC
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Silver - The Underrated Investment
- Simple Morningstar Fund Report Script
- Sølv - den undervurderte investeringen
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API