Powershell – Hidden Features of PowerShell

powershell

What are the hidden features of PowerShell?

Best Answer

Force Powershell functions to really return an array, even an empty array.

Due to the way the @() syntax is implemented, functions may not always return an array as expected, e.g. the following code will return a $null and NOT an empty array. If you are testing code with set-StrictMode -On set, you'll get an PropertyNotFoundStrict error instead when trying to reference the .count property:

function test
{
    #some code that might return none,one or multiple values
    $data = $null
    return @($data)
}
(test).count

Simply prepending a , to the @() will bypass the "syntactic sugar" and you'll have an actual array returned, even if it's empty:

function test2
{
    #some code that might return none,one or multiple values
    $data = $null
    return ,@($data)
}
(test2).count