Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable is a string list/array?

Tags:

powershell

The following code returns True. What's the correct way to check the type in PowerShell?

$e = @(1,2)
$e -ne $null -and $e.GetType() -eq (@("")).GetType()

Update:

The following code will return false. It's expected to be true.

$e = @('1','2')
$e -is [string[]]
like image 918
ca9163d9 Avatar asked Apr 25 '26 06:04

ca9163d9


1 Answers

You can use the -is operator to check the type to check if it's an array:

$arr = 1, 2
$arr -is [array]

However, it is probably more prudent to check that the object implements IEnumerable, since there are many collection types that are not specifically arrays but are iterable:

$arr = 1, 2
$arr -is [System.Collections.IEnumerable]

Also note that if you assign the result of a cmdlet/function to a variable that can return more than one element, but it only returns a collection with a single element, by default it will be unrolled and assigned as a single value. You can force a returned collection to be evaluated/assigned as an array with one of the following techniques (using Get-Process as an example of this):

$arr = @( Get-Process iexplore ) # ===========> Forces the returned value to be part of a collection,
                                 #              even if only a single process is returned.
$arr -is [System.Collections.IEnumerable] # ==> true

or you can use the , notation to force the returned values to be evaluated as a collection as well (you will need to sub-express your cmdlet/function call in this case):

$arr = , ( Get-Process iexplore )
$arr -is [System.Collections.IEnumerable]

If you are checking a generic collection (a collection whose type is defined within the System.Collections.Generic namespace), you can also check against the collection's associated type using System.Collections.Generic.IEnumerable[T] instead, where T is the type of element allowed in the array. For example:

$list = New-Object System.Collections.Generic.List[string]
$list -is [System.Collections.Generic.IEnumerable[string] # ==> true
like image 57
Bender the Greatest Avatar answered Apr 27 '26 20:04

Bender the Greatest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!