PowerShell: Setting an environment variable for a single command only

前端 未结 8 874
闹比i
闹比i 2020-11-29 02:17

On Linux, I can do:

$ FOO=BAR ./myscript

to call \"myscript\" with the environment variable FOO being set.

Is something similar pos

相关标签:
8条回答
  • 2020-11-29 03:21

    You could do this by running the script as a Job:

    Start-Job -InitializationScript { $env:FOO = 'BAR' } -FilePath .\myscript.ps1 |
        Receive-Job -Wait -AutoRemoveJob
    

    You could also pass arguments to the script, using the ArgumentList parameter of Start-Job:

    $jobArgs = @{
        InitializationScript = { $env:FOO = 'BAR' } 
        FilePath             = '.\myscript.ps1'
        ArgumentList         = 'arg1', 'arg2' 
    }
    Start-Job @jobArgs | Receive-Job -Wait -AutoRemoveJob
    

    Advantages and disadvantages

    • You don't have to reset the environment variable after the script finishes (which would require try / finally to do it correctly even in the presence of exceptions).
    • The environment variable will be really local to the launched script. It won't affect other, possibly launched in parallel, jobs.
    • The script will run in its own, somewhat isolated environment. This means that the launched script can't set variables of the main script, it will have to use Write-Output to communicate back to the main script. This could be an advantage or a disadvantage, depending on the use case.
    0 讨论(0)
  • 2020-11-29 03:22

    Considering that CMD is the native CLI on the Windows kernel (and is still the automation interface for lots of tools), you may be executing your PowerShell script with powershell.exe from the CMD prompt or an interface that accepts CMD console statements.

    If you are using the -File parameter to pass your script to powershell.exe, no other PowerShell code can be used to set an environment variable for the script to access, so instead you can set your environment variables in the CMD environment before calling powershell.exe:

    > set foo=bar && powershell.exe -File .\script.ps1
    

    A single & will also work, but will allow the command to continue if the set failed for some reason. (Is this even possible? I have no idea.)

    Also, it may be safer to wrap "foo=bar" in quotes so that nothing following gets passed to set as the variable contents.

    0 讨论(0)
提交回复
热议问题