Powershell scripts can be used to execute SQL Scripts. The below scripts can be used to run all the .sql scripts from a directory. I did not use sort-object , that means the files will run in ascending order.
#Provide SQLServerName $SQLServer ="MySQLSErver\InstanceName" #Provide Database Name $DatabaseName ="Test" #Scripts Folder Path $FolderPath ="C:\MyScripts\Test\" #Loop through the .sql files and run them foreach ($filename in get-childitem -path $FolderPath -filter "*.sql") { invoke-sqlcmd –ServerInstance $SQLServer -Database $DatabaseName -InputFile $filename.fullname #Print file name which is executed $filename
}
If you would like to run the script in descending order you can use below script
#Provide SQLServerName $SQLServer ="MySQLSErver\InstanceName" #Provide Database Name $DatabaseName ="Test" #Scripts Folder Path $FolderPath ="C:\MyScripts\Test\" #Loop through the .sql files and run them foreach ($filename in get-childitem -path $FolderPath -filter "*.sql" |sort-object
-descending)
{
invoke-sqlcmd –ServerInstance $SQLServer -Database $DatabaseName -InputFile $filename.fullname
#Print file name which is executed
$filename
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.