Is there a way to execute an arbitrary query on a SQL Server using Powershell on my local machine?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- How to Debug/Register a Permanent WMI Event Which
- php PDO::FETCH_ASSOC doesnt detect select after ba
For others who need to do this with just stock .net and PowerShell (no additional SQL tools installed) here is the function that I use:
I have been using this so long I don't know who wrote which parts but this was distilled from other's examples but simplified to be clear and just what is needed without extra dependencies or features.
I use and share this often enough that I have turned this into a script module on GitHub so that you can now go to your modules directory and execute
git clone https://github.com/ChrisMagnuson/InvokeSQL
and from that point forward invoke-sql will automatically be loaded when you go to use it (assuming your using powershell v3 or later).There isn't a built-in "PowerShell" way of running a SQL query. If you have the SQL Server tools installed, you'll get an Invoke-SqlCmd cmdlet.
Because PowerShell is built on .NET, you can use the ADO.NET API to run your queries.
You can use the
Invoke-Sqlcmd
cmdlethttp://technet.microsoft.com/en-us/library/cc281720.aspx
If you want to do it on your local machine instead of in the context of SQL server then I would use the following. It is what we use at my company.
Just fill in the $ServerName, $DatabaseName and the $Query variables and you should be good to go.
I am not sure how we originally found this out, but there is something very similar here.
This function will return the results of a query as an array of powershell objects so you can use them in filters and access columns easily: