Jump to page sections
- Remove and consider only $null as empty
- Remove and consider only empty strings as empty, keeping $null
- Remove and consider $null and empty strings as empty elements
- Remove and consider $null, empty strings and whitespace-only strings as empty
- A regex alternative
You will typically define empty as $null, an empty string, a string consisting only of whitespace, or a combination of two or more of these.
I'm using Where-Object to demonstrate here, but these are just examples. Remember that you can put the code I show you inside foreach loops or ForEach-Object if that's more suitable and/or efficient in your case, inside an if () {} statement. This is more efficient in many cases as someone pointed out. Where-Object seems obvious for demonstrational purposes.Remove and consider only $null as empty
I'll show you the PSv4 and up way now, but will from then on stick to PSv2 syntax, to be friendlier to people stuck in non-optimal environments with older software (trust me, it happens).
I'll be using a four-element array that represents all the cases. Here's the PSv4 syntax for the optimized .Where({}).Since we're only filtering out $null, the expected count of elements remaining in the list/array should be 3, and as we can see, it is.
Putting $null on the left side of the comparison is necessary if you have a potentially nested array, so I will use the best-practice form in this example.PS C:\> $Array = @("", " ", $null, "a")
PS C:\> $Array.Count
4
PS C:\> $NewArray = $Array.Where({ $null -ne $_ })
PS C:\> $NewArray.Count
3
Here's the same example using the PSv2-compatible syntax I'll stick to from now on.
PS C:\> ($Array | Where { $null -ne $_ }).Count
3
Remove and consider only empty strings as empty, keeping $null
This will keep the space, $null and the letter, and should give a count of 3. It does.
PS C:\> (@("", " ", $null, "a") | Where { $_ -ne "" }).Count
3
Remove and consider $null and empty strings as empty elements
Both $null and empty strings are considered false, so you can actually just throw the pipeline object into the Where-Object script block.
Here we should get a count of two elements, the space and the letter, and we do. PS C:\> @(@("", " ", $null, "a") | Where { $_ }).Count
2
I will demonstrate an explicit way as well. If you have integers with the numeric value "0" in the array, they will also be considered false, so if this is relevant, and you want to keep those, use this:
PS C:\> @(@("", " ", $null, "a") | Where { $null -ne $_ -and $_ -ne ""}).Count
2
Another explicit way that's v2-/.NET 3.5-compatible is to use the [string]::IsNullOrEmpty("string here") method:
PS C:\temp> @(@("", " ", $null, "a") | Where { -not [string]::IsNullOrEmpty($_) }).Count
2
Remove and consider $null, empty strings and whitespace-only strings as empty
Since $null and empty are considered false, we can use that to filter, and you might think that running the System.String.Trim() method on the string is a good idea - and it's not bad, except it produces an error for the $null element (can't call method on a null-valued expression).
To work around this, you can simply check for truth first, and then Trim(), removing all whitespace. If there is nothing else in the string, this leaves you with an empty string that will be considered false, and thus the element will be filtered out by Where-Object when the last condition returns false.PS C:\> (@("", " ", $null, "a") | Where { $_ -and $_.Trim() }).Count
1
PS C:\> @("", " ", $null, "a") | Where { $_ -and $_.Trim() }
a
In PowerShell version 3 and up (.NET framework 4 and up), you can also access the System.String class' method ''IsNullOrWhiteSpace()'', to do exactly the same (it returns true for empty strings too):
PS C:\> @("", " ", $null, "a") | Where { -not [string]::IsNullOrWhiteSpace($_) }
a
PS C:\>
A regex alternative
To make sure a string contains something that isn't whitespace, you can also use the regular expression "\S". This is the complement of all characters included in the "whitespace" regex class, meaning one instance of any non-whitespace character.
You could for instance use it like this, and it is logically equivalent to considering $null, empty strings, and whitespace-only strings empty.PS C:\> (@("", " ", $null, "a") | Where { $_ -match '\S' }).Count
1
PS C:\> @("", " ", $null, "a") | Where { $_ -match '\S' }
a
Powershell
Windows
Regex
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