I’m using Powershell to set up IIS bindings on a web server, and having a problem with the following code:
$serverIps = gwmi Win32_NetworkAdapterConfiguration
| Where { $_.IPAddress }
| Select -Expand IPAddress
| Where { $_ -like '*.*.*.*' }
| Sort
if ($serverIps.length -le 1) {
Write-Host "You need at least 2 IP addresses for this to work!"
exit
}
$primaryIp = $serverIps[0]
$secondaryIp = $serverIps[1]
If there’s 2+ IPs on the server, fine – Powershell returns an array, and I can query the array length and extract the first and second addresses just fine.
Problem is – if there’s only one IP, Powershell doesn’t return a one-element array, it returns the IP address (as a string, like “192.168.0.100”) – the string has a .length property, it’s greater than 1, so the test passes, and I end up with the first two characters in the string, instead of the first two IP addresses in the collection.
How can I either force Powershell to return a one-element collection, or alternatively determine whether the returned “thing” is an object rather than a collection?
Define the variable as an array in one of two ways…
Wrap your piped commands in parentheses with an
@at the beginning:Specify the data type of the variable as an array:
Or, check the data type of the variable…