Powershell skip element in array, if it blank Powershell skip element in array, if it blank powershell powershell

Powershell skip element in array, if it blank


It's easiest to use -ne '' to created a filtered copy of the array that excludes empty entries, courtesy of the ability of many PowerShell operators to act as a filter with an array-valued LHS.

Note: I'm assuming you mean to filter out empty strings, not also blank (all-whitespace) ones, given that undefined environment variables expand to an empty string.

# Sample array with empty elements.# Note: No need for @(...), unless there's just *one* element.$IISarray = "foo", "", "bar", "baz", ""# Note the `-ne ''`, which filters out empty elements.foreach ($string in $IISarray -ne ''){   $string # echo}

The above yields:

foobarbaz

soundstripe's answer offers a Where-Object solution, which potentially provides added flexibility via the ability to specify an arbitrary filter script block, but the use of a pipeline is a bit heavy-handed for this use case.
Fortunately, PSv4+ offers the .Where() collection method, which performs noticeably better.

Let me demonstrate it with a solution that also rules out blank (all-whitespace) elements:

# Note the all-whitespace element, which we want to ignore too.PS> ("foo", "   ", "bar", "baz", "").Where({ $_.Trim() })foobarbaz

Similar to the Where-Object cmdlet, you pass a script block to the .Where() method, inside of which the automatic $_ variable represents the input element at hand.

The .Trim() method trims leading and trailing whitespace from a string and returns the result.
An all-whitespace string therefore results in the empty string.

In a Boolean context (as the .Where() method script block implicitly is), the empty string evaluates to $false, whereas any non-empty string is $true.
You can choose to be explicit, however ($_.Trim() -ne ''), or even use a .NET method ([string]::IsNullOrWhiteSpace($_)).


You can use Where-Object to filter out null or empty values. It is very commonly used, so ? is shorthand for Where-Object.

$IISarray = @("$ENV:Cashier_NAME", "$ENV:Terminal_NAME", "$ENV:Content_Manager_NAME", "$ENV:Kiosk_BO_NAME")foreach ($string in ($IISarray | ? {$_})){"some code goes here"}

The $_ is an automatic variable representing each incoming object in the pipeline. Both $null and the empty string '' are falsy in Powershell, so only non-null values with length > 0 will be passed in to your for loop.


# you can skip the `@` and brackets as well as the quotation marks$IISarray = $ENV:Cashier_NAME, $ENV:Terminal_NAME, $ENV:Content_Manager_NAME, $ENV:Kiosk_BO_NAMEforeach($String in $IISarray) {    # trim the strings and check the length    if($String.Trim().Length -gt 0) {        "some code goes here"    }}