Wednesday 15 April 2015

Reset to original script directory in PowerShell

I've been write several PowerShell scripts lately to help automate repetitive tasks. When I've been testing these scripts, I will often change my current location with in PowerShell, either cd to another location or fire up the SqlServer shell.

When the script finished during test, I would then make another change, add the next step etc, then go to my PowerShell console, but it's not in the original directory for me to re-run my script.

I've taken to adding the following to the bottom of my scripts to return the console back to the original location.

# Switch back to disk prompt
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
Set-Location -Path $scriptPath


I know there are many ways of doing this in PowerShell, but I'm still learning.

No comments: