How To Execute a SQL Script from Powershell

Published: 03 May 2022
on channel: The SQL Guy
11,268
42

In this tutorial we look at how to execute a SQL script from Powershell. I cover how to use both powershell ISE and Powershell CMD.

Lesson Format

00:00 Tutorial overview
00:43 Executing SQL with Powershell script
02:00 Catching Errors and Logging
04:25 Using Powershell CMD

Creating the SQL Table

In the tutorial I go over how to create a SQL Table with a timestamp column that shows when the record was inserted. This is good for both demonstrating that the script is actually doing what I want it to, but also highlighting when the record is inserted.

Along with the Create Table syntax, I also show the relevant INSERT statement we are using and save the file along with the Powershell script.

Powershell Script

The powershell script is simple Invoke-sqlcmd cmdlet. This passes in the database instance along with the server name and an input file. Later in the tutorial we look at how add logging within this also.

Its really nice and simple - just 3 lines of code (it could even be done in 1!)

Logging errors

Within the tutorial I also look at how to catch any errors that may occur while we run the script, we may be automating this process and have it running on a schedule for example. To do this we can create a nice log file which captures any errors which we could potentially check should we not be getting the required results.

Requests

If there is anything else that you need or want answered then please let me know and I can get it answered or a video made.

Thanks - please Like and Subscribe


On this page of the site you can watch the video online How To Execute a SQL Script from Powershell with a duration of hours minute second in good quality, which was uploaded by the user The SQL Guy 03 May 2022, share the link with friends and acquaintances, this video has already been watched 11,268 times on youtube and it was liked by 42 viewers. Enjoy your viewing!