Reputation: 745
I have a powershell script that does a Invoke-Sqlcmd and when the script completes it leaves me in 'SQLSERVER:>'.
Is there a way to tell my script to return me to original directory when it completes?
Upvotes: 0
Views: 75
Reputation: 47792
My preferred method is to do this:
try {
Push-Location
Import-Module SQLPS
# More code
} finally {
Pop-Location
}
This is especially nice during testing because even when you throw an exception or stop the debugger your original path is still restored.
Upvotes: 0
Reputation: 129
Import-Module SQLPS -DisableNameChecking | Out-Null
Push-Location "SQLSERVER:\sql\$Server\DEFAULT\databases\$database" | Out-Null
Invoke-Sqlcmd -Query $query
#More Work
pop-location
Alternatively you could push the location of the database you want to run queries/operations onto the location stack. Do work. Then pop the location off the location stack when done.
$Server : Being the server the db is being hosted on $database : The database name in your database server
The Out-Null isn't required. It just prevents output being pumped into the pipeline
Upvotes: 1
Reputation: 7638
The canonical method for this is:
try {
$private:oldLocation = (Get-Location)
# Do Stuff
}
finally {
Set-Location $private:oldLocation
}
Upvotes: 1