Powershell Gems: Destructuring

Destructuring

What is destructuring?

Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

source

Here is an example of destructuring in powershell.

$first, $second, $therest = 1,2,3,4,5
$first
1
$second
2
$therest
3
4
5

As you can see, Powershell assigns the first and second values in the array to the variables $first and $second. The remaining items are then assigned to the last variable in the assignment list.

Gotchas

If we look at the following Powershell code nothing seems out of the ordinary.

$arr = @(1)
$arr.GetType().FullName
System.Object[]

However, look at this code sample:

# When Function Returns No Elements
Function Get-Array() { 
    return @() 
} 
$arr = Get-Array
$arr.GetType()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $arr.GetType()
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

$arr -eq $null
True

# When Function Returns One Element
Function Get-Array() { 
    return @(1)  
}
$arr = Get-Array
$arr.GetType().FullName
System.Int32

# When Function Returns Multiple Elements
Function Get-Array() { 
    return @(1,2)
} 
$arr = Get-Array
$arr.GetType().FullName
System.Object[]

When returning arrays from functions, if the array contains only a single element, the default Powershell behavior is to destructure it. This can sometimes lead to confusing results.

You can override this behavior by prepending the resultant array with a ‘,’ which tells Powershell that the return type should not be destructured:

# When Function Returns No Elements
Function Get-Array() {
    return ,@() 
} 
$arr = Get-Array
$arr.GetType().FullName
System.Object[]

# When Function Returns One Element
Function Get-Array() {
    return ,@(1) 
} 
$arr = Get-Array
$arr.GetType().FullName
System.Object[]

# When Function Returns Multiple Elements
Function Get-Array() {
    return ,@(1,2)
}
$arr = Get-Array
$arr.GetType().FullName
System.Object[]

Leave a Reply

%d bloggers like this: