Powershell: Shorthand Operator does not work inside function

Created on 5 Sep 2019  路  2Comments  路  Source: PowerShell/PowerShell

Steps to reproduce

Param (
[Parameter(Mandatory=$true)]
[string[]] $t
)

Function test {
$empty = @()

$t += $empty

Write-Host $t
}

test

Expected behavior

should append input arguments with empty array

Actual behavior

assigns empty array instead of appending the empty array

Environment data

PSVersion                      5.1.18362.145
Issue-Question Resolution-Answered

Most helpful comment

You're implicitly creating a _function-local_ $t variable inside your test function, which goes out of scope when the function is exited - the _script-level_ $t is never modified.

In an _assignment_, you'd have to refer to the script-level $t variable as $script:t, for instance.

(However, on _retrieval_ of the script-level $t value, $t is sufficient (unless you're shadowing it with a local $t). This asymmetry is a common pitfall - see this StackOverflow answer for details.)

All 2 comments

You're implicitly creating a _function-local_ $t variable inside your test function, which goes out of scope when the function is exited - the _script-level_ $t is never modified.

In an _assignment_, you'd have to refer to the script-level $t variable as $script:t, for instance.

(However, on _retrieval_ of the script-level $t value, $t is sufficient (unless you're shadowing it with a local $t). This asymmetry is a common pitfall - see this StackOverflow answer for details.)

This issue has been marked as answered and has not had any activity for 1 day. It has been closed for housekeeping purposes.

Was this page helpful?
0 / 5 - 0 ratings