2

Coming from the Unix world, scripts when executed (as opposed to sourced) are run in a subshell, and thus variable declarations and cd commands do not affect the actual current session (the one where we type our commands).

For reference:

# Executing a script
./myscript.ps1

# Sourcing a script
. ./myscript.ps1

Very surprised (and quite frankly annoyed) to see than in Powershell, executing a script will still affect my current session regarding cd commands (but not declared variables).

How can I prevent this from happening ?

phuclv
  • 37,963
  • 15
  • 156
  • 475
adamency
  • 682
  • 6
  • 13
  • 1
    the working dir is the one that the system sees as "current". of _course_ it changes the location that _anything_ sees as current. [*grin*] – Lee_Dailey May 01 '22 at 05:01
  • 2
    Scripts are executed in the current session, that's the way it is. Either use `pushd` and `popd` pairs instead of `cd`, or a `try { $initialDirectory = pwd; ... }`/`finally { cd $initialDirectory }` wrapper, or explicitly start a new powershell process to run your script. – Tomalak May 01 '22 at 05:49
  • Yes that's what I've been doing as an alternative, but thanks anyway :). However I still feel this is a dubious behavior design, as variable declarations are still not propagated in the current session when *executing* the script, as opposed to *sourcing* it. So the execution isn't actually in the current session, it's a hybrid behavior between executing and sourcing. – adamency May 03 '22 at 10:39

0 Answers0