Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Invoke-Sqlcmd switches into sqlps session

Tags:

I am writing a script in PowerShell ISE and I am using Invoke-Sqlcmd. After the command is executed the Powershell session switches into sqlps session (PS SQLSERVER:>) and I can't execute script for the second time. I have to quit PowerShell ISE and start it again.

So my question is: how to switch back from sqlps to regular ps or how to prevent Invoke-Sqlcmd from switching session.

Invoke-Sqlcmd -ServerInstance $server -Database master -Username $user -Password $password   -InputFile $file `    -ErrorAction Stop -OutputSqlErrors $true -Variable $variable 

This doesn't work:

Push-Location Invoke-Sqlcmd -ServerInstance $server -Database master -Username $user -Password $password   -InputFile $file ` -ErrorAction Stop -OutputSqlErrors $true -Variable $variable Pop-Location 
like image 291
scar80 Avatar asked Jun 11 '14 13:06

scar80


People also ask

What does invoke-SqlCmd function do in PowerShell?

The Invoke-Sqlcmd cmdlet runs a script containing the languages and commands supported by the SQL Server SQLCMD utility. The commands supported are Transact-SQL statements and the subset of the XQuery syntax that is supported by the database engine.


1 Answers

The sqlps module's behavior is to leave you in the psdrive that it creates. I'm fairly certain that people have asked Microsoft to fix this, as it's very annoying and disruptive.

The automatic importing of modules introduced by PowerShell 3.0 makes this even more annoying, because you may not even realize that you're importing the module until after the fact.

When I use sqlps, I explicitly import it so that I can control my working directory as follows:

push-location import-module sqlps -disablenamechecking pop-location 

This returns you to your previous directory after the module is loaded.

Very late edit: With the advent of SQL Server Management Studio 2016 we have a new PowerShell module, sqlserver, which supersedes sqlps and resolves this problem.

like image 72
alroc Avatar answered Sep 30 '22 09:09

alroc