What is the setlocal / endlocal equivalent for PowerShell?

后端 未结 4 2255
时光说笑
时光说笑 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:42

    I would probably just use a try { } finally { }:

    try {
        $OriginalValue = $env:MYLANG
        $env:MYLANG= 'GB'
        my-cmd dostuff -o out.csv
    }
    finally {
        $env:MYLANG = $OriginalValue
    }
    

    That should force the values to be set back to their original values even if an error is encountered in your script. It's not bulletproof, but most things that would break this would also be very obvious that something went wrong.

    You could also do this:

    try {
        $env:MYLANG= 'GB'
        my-cmd dostuff -o out.csv
    }
    finally {
        $env:MYLANG = [System.Environment]::GetEnvironmentVariable('MYLANG', 'User')
    }
    

    That should retrieve the value from HKEY_CURRENT_USER\Environment. You may need 'Machine' instead of 'User' and that will pull from HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment. Which you need depends if it's a user environment variable or a computer environment variable. This works because the Env: provider drive doesn't persist environment variable changes, so changes to those variables won't change the registry.

提交回复
热议问题