Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Kevin-Bronsdijk/55d369da587715c55daf to your computer and use it in GitHub Desktop.
Save Kevin-Bronsdijk/55d369da587715c55daf to your computer and use it in GitHub Desktop.
executing-sql-statements-using-powershell2
Import-Module SQLPS -DisableNameChecking
#replace your with your instance name
$instanceName = "server\instance";
$srv = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName;
#replace your with your user database name
$dbName = "name_user_db"
$db = $srv.Databases[$dbName]
#Similar to a ado.net execute non query
Invoke-Sqlcmd `
-ServerInstance "$instanceName" `
-Database $dbName `
-Query "INSERT INTO [dbo].[test1] ([column1]) VALUES (1)"
#execute query and export to a CSV
Invoke-Sqlcmd `
-ServerInstance "$instanceName" `
-Database $dbName `
-Query "SELECT TOP 1000 [column1],[id] FROM [dbo].[test1]" |
Export-Csv -LiteralPath "C:\results.csv" `
-NoTypeInformation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment