Execute .SQL Files from Main Folder and Sub Folders by using PowerShell

The below script can be used to run multiple .sql files which resides in sub folders or in your main folder. It is very common to manager .sql files in sub folders for projects and as DBA we often have to deploy all the sql scripts from Main folder and Sub Folder. It is really pain if we have to open each of the folder and deploy the scripts. This is short script that can help to deploy all the .SQL Files to your Server.

In the Script you have to change the ServerName, Database Name and Location of your SQL Files.

#Provide SQLServerName
$SQLServer ="ComputerName\InstanceName"
#Provide Database Name 
$DatabaseName ="Test"
#Scripts Folder Path
$FolderPath ="C:\PowerShell\SQLScripts\"

#Loop through the .sql files and run them
foreach ($filename in get-childitem -path $FolderPath -recurse -file -filter "*.sql" | 
invoke-sqlcmd –ServerInstance $SQLServer -Database $DatabaseName -InputFile 
#Print file name which is executed