Variable scoping in PowerShell

后端 未结 4 1720
日久生厌
日久生厌 2020-12-02 18:21

A sad thing about PowerShell is that function and scriptblocks are dynamically scoped.

But there is another thing that surprised me is that variables behave as a cop

4条回答
  •  情话喂你
    2020-12-02 18:48

    You can use scope modifiers or the *-Variable cmdlets.

    The scope modifiers are:

    • global used to access/modify at the outermost scope (eg. the interactive shell)
    • script used on access/modify at the scope of the running script (.ps1 file). If not running a script then operates as global.

    (For the -Scope parameter of the *-Variable cmdlets see the help.)

    Eg. in your second example, to directly modify the global $array:

    & {
      $global:array +="s"
      Write-Host $array
    }
    

    For more details see the help topic about_scopes.

提交回复
热议问题