Bash/batch-like subshell in Powershell
You can invoke powershell directly to spawn a true subshell (i.e. outer shell's state is not modified by the subshell):
pwsh -Command { cmd1 ; cmd2 } | cmd3
Since powershell takes objects instead of just strings as input, the -Command
argument can take a script block. Be aware thst there is some strange behavior if you try to write to non-success, nom-error streams, such as with Write-Host
. If you run into these issues, I found it's easiest to just emulate a subshell with a function that saves all relevant state, executes its argument with Invoke-Command
or &
, then restores the state.