What is the setlocal / endlocal equivalent for PowerShell?

后端 未结 4 2252
时光说笑
时光说笑 2021-02-15 15:24

Objective

Isolate environmental variable changes to a code block.

Background

If I want to create a batch scrip

4条回答
  •  无人及你
    2021-02-15 15:41

    There is a way to achieve this in PowerShell:

    Local Scope:

    & { [System.Environment]::SetEnvironmentVariable('TEST', 'WORK Local', [System.EnvironmentVariableTarget]::Process)
    [System.Environment]::GetEnvironmentVariable("TEST", [System.EnvironmentVariableTarget]::Process) }
    

    This creates the environmental variable in the scope of the process same as above. Any call to it outside the scope will return nothing.

    For a global one you just change the target to Machine:

    & { [System.Environment]::SetEnvironmentVariable('TEST', 'WORK Global', [System.EnvironmentVariableTarget]::Machine) }
    

    Any call to this outside the scope will return 'Work Global'

    Putting it all together:

    ## create local variable and print
    & { [System.Environment]::SetEnvironmentVariable('TEST', 'WORK Local', [System.EnvironmentVariableTarget]::Process)
    [System.Environment]::GetEnvironmentVariable("TEST", [System.EnvironmentVariableTarget]::Process) }
    
    
    function tt {
      ($env:TEST)
    }
    
    & { $TEST="EN"; $env:TEST="EN"; tt }
    & { $TEST="change1"; $env:TEST="change1"; tt }
    & { $TEST="change1"; $env:TEST="change2"; tt }
    
    [System.Environment]::GetEnvironmentVariable("TEST", [System.EnvironmentVariableTarget]::Process)
    
    & { [System.Environment]::SetEnvironmentVariable('TEST', 'WORK Global', [System.EnvironmentVariableTarget]::Machine) } ## create global variable
    
    ## Create local variable and print ( overrides global )
    & { [System.Environment]::SetEnvironmentVariable('TEST', 'WORK Local', [System.EnvironmentVariableTarget]::Process)
    [System.Environment]::GetEnvironmentVariable("TEST", [System.EnvironmentVariableTarget]::Process) }
    
    [System.Environment]::GetEnvironmentVariable("TEST", [System.EnvironmentVariableTarget]::Machine) ## get global variable
    
    [System.Environment]::SetEnvironmentVariable("TEST",$null,"USer") ## remove global variable
    

    This gives us the following output:

    WORK Local
    EN
    change1
    change2
    change2
    WORK Local
    WORK Global
    

提交回复
热议问题