I have a .sql
file. I am trying to pass connection string details through a Powershell script and invoke an .sql
file.
I was searching and came up with a cmdlet related to Invoke-sqlcmd
. While I was trying to find a module corresponding to SQL, I did not find any one in my machine.
Should I install anything in my machine (the machine already has SQL Server Management Studio 2008 R2) to get the modules or is there any easy way to execute .sql
files using Powershell?
Quoting from Import the SQLPS Module on MSDN,
So, yes, you could use the
Add-PSSnapin
approach detailed by Christian, but it is also useful to appreciate the recommended sqlps module approach.The simplest case assumes you have SQL Server 2012: sqlps is included in the installation so you simply load the module like any other (typically in your profile) via
Import-Module sqlps
. You can check if the module is available on your system withGet-Module -ListAvailable
.If you do not have SQL Server 2012, then all you need do is download the sqlps module into your modules directory so Get-Module/Import-Module will find it. Curiously, Microsoft does not make this module available for download! However, Chad Miller has kindly packaged up the requisite pieces and provided this module download. Unzip it under your ...Documents\WindowsPowerShell\Modules directory and proceed with the import.
It is interesting to note that the module approach and the snapin approach are not identical. If you load the snapins then run
Get-PSSnapin
(without the -Registered parameter, to show only what you have loaded) you will see the SQL snapins. If, on the other hand, you load the sqlps moduleGet-PSSnapin
will not show the snapins loaded, so the various blog entries that test for theInvoke-Sqlcmd
cmdlet by only examining snapins could be giving a false negative result.2012.10.06 Update
For the complete story on the sqlps module vs. the sqlps mini-shell vs. SQL Server snap-ins, take a look at my two-part mini-series Practical PowerShell for SQL Server Developers and DBAs recently published on Simple-Talk.com where I have, according to one reader's comment, successfully "de-confused" the issue. :-)
with 2008 Server 2008 and 2008 R2
with 2012 and 2014
Try to see if SQL snap-ins are present:
If so
then you can do something like this:
Here is a function that I have in my PowerShell profile for loading SQL snapins: