I had a script that assumes something was an array, then failed when it wasn’t, so I needed a little checking:
$variable -is [system.array]
will say True if it is an array, or False if not. You can also do $variable -isnot [system.array]
and expect the exact opposite.
I chose to do this:
1 |
if($variable -isnot [system.array]){do some code expecting the $variable is not an array} |
OR
1 |
if($variable -is [system.array]){do some other stuff with $variable[0] being an array} |
Why not use ‘else’?
The script I used this in uses if and else, I just needed to know up front if it was an array or not.
what about
if($variable -isnot [system.array]) { $variable = @($variable)}
Then you never have to write this conditional anywhere else lower down in your code either, I know its a kludge, because it modifies the data, but it’s a happy one.
That’s another way that would work. Thanks for the tip!
Really handy tip, thanks.
Thanks. This just cured my head banging.
Thanks a lot!
I was splitting strings on a character and if the character was found I got a string array back, else just the original string. Since I wanted to get only the first part of the split string – this helps. doing $var[0] does not work for non array strings since it returns the first character only. Now I can return $var if it is not an array and $var[0] if it is an array
if ($t -isnot [system.array])
{
$t
}
else
{
$t[0]
}
Thank you very much … saved my life. Thank you!