On Linux, I can do:
$ FOO=BAR ./myscript
to call \"myscript\" with the environment variable FOO being set.
Is something similar pos
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
try
/ finally
to do it correctly even in the presence of exceptions).Write-Output
to communicate back to the main script. This could be an advantage or a disadvantage, depending on the use case.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.