How to run sql script using powershell?

Question:

I wanted to run a sql script using powershell but getting an error “The term ‘Invoke-sqlcmd’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check t
he spelling of the name, or if a path was included, verify that the path is correct and try again.”

I have found the below snippet from some website.but this is only for one sql command..But i wanted to run a sql script.

Could someone please help in modifying the below for sql script or any better suggestion ?

Answer:

You can use your code as it is, just put your SQL script in a Here-String (string literal). In addition I would wrap the call to the SQL database in a Try/Catch/Finally construct to ensure your connections are closed and disposed. Finally, consider using Application Name in your connection string to give your DBA’s a clue as to what your connection is related to. Putting that together:

Source:

How to run sql script using powershell? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply