0

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?

3 Answers 3

1

The canonical method for this is:

try {
    $private:oldLocation = (Get-Location)

    # Do Stuff

}
finally {
    Set-Location $private:oldLocation
}
Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.