How to reset current directory after closing powershell script
I had batch script for running NPM which when simplified looks like this:
cd ./subfolder
call npm run dev
Then after launching it inside Powershell, NPM server was running. When I press Ctrl+C twice to close it, my current directory is left as it was, which is fine. However, later I needed more sophisticated tasks in the script and I changed it to Powershell script, which when simplified looks like this:
Set-Location ./subfolder
npm run dev
But now when I run it from Powershell and close, my working directory is left at "subfolder", which is really annoying!
Does anybody know how to solve it, so Powershell script behaves the same as batch file?
EDIT: I noticed, that opposite is true, if I call batch script from Command Prompt, then current directory is also kept at "subfolder".
EDIT2: I tried putting Set-Location ..
in the end. The problem is that when I press Ctrl+C to close NPM (it is never-ending process), not only NPM is closed, but also powershell script, therefore last command is never reached.
As a improvement of the suggestion by DavidPostill, you may use the PowerShell TRY/FINALLY commands to gracefully terminate the script:
try
{
pushd ./subfolder
npm run dev
}
finally
{
write-host "Ended work."
popd
}