How can I force Powershell to return an array when a call only returns one object?

Define the variable as an array in one of two ways…

Wrap your piped commands in parentheses with an @ at the beginning:

$serverIps = @(gwmi Win32_NetworkAdapterConfiguration 
    | Where { $_.IPAddress } 
    | Select -Expand IPAddress 
    | Where { $_ -like '*.*.*.*' } 
    | Sort)

Specify the data type of the variable as an array:

[array]$serverIps = gwmi Win32_NetworkAdapterConfiguration 
    | Where { $_.IPAddress } 
    | Select -Expand IPAddress 
    | Where { $_ -like '*.*.*.*' } 
    | Sort

Or, check the data type of the variable…

IF ($ServerIps -isnot [array])
{ <error message> }
ELSE
{ <proceed> }

Leave a Comment