Created
June 9, 2022 06:01
-
-
Save rollendxavier/76d982f27e523ae1bf31dcbaacbdd9aa to your computer and use it in GitHub Desktop.
Use the Invoke-Sqlcmd to run a script containing statements supported by the SQL Server SQLCMD utility.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| param( | |
| [Parameter(Mandatory=$True, Position=0)] | |
| [System.String] | |
| $Server, | |
| [Parameter(Mandatory=$True, Position=1)] | |
| [System.String] | |
| $Database, | |
| [Parameter(Mandatory=$True, Position=2)] | |
| [System.String] | |
| $UserName, | |
| [Parameter(Mandatory=$True, Position=3)] | |
| [System.String] | |
| $Password, | |
| [Parameter(Mandatory=$True, Position=4)] | |
| [System.String] | |
| $Scriptpath, | |
| [Parameter(Mandatory=$True, Position=5)] | |
| [System.String] | |
| $Includesubfolders | |
| ) | |
| Function IsDBInstalled() | |
| { | |
| Write-host "Trying to connect [$Database] in SQL Server [$Server]" -BackgroundColor blue -ForegroundColor black | |
| $t=Invoke-Sqlcmd -ServerInstance $Server -Username $UserName -Password $Password -Database "master" -Query "select 1 from sys.databases where name='$Database'" -OutputSqlErrors $true | |
| if (!$t) { | |
| Write-Host "Failed to connect to [$Database] database on [$Server]" -BackgroundColor darkred | |
| Write-Error "Failed to connect to [$Database] database on [$Server]" -ErrorAction Stop | |
| } else { | |
| write-host "[$Database] Database exists in SQL Server [$Server]" -BackgroundColor blue -ForegroundColor black | |
| } | |
| } | |
| IsDBInstalled | |
| if($Includesubfolders -eq "true") { | |
| $subscripts = Get-ChildItem $Scriptpath -recurse | Where-Object {$_.Extension -eq ".sql"} | |
| foreach ($s in $subscripts) | |
| { Write-Host "Running Script : " $s.Name -BackgroundColor green -ForegroundColor darkRed | |
| $tables=Invoke-Sqlcmd -ServerInstance $Server -Username $UserName -Password $Password -Database $Database -InputFile $s.FullName -ErrorAction 'Stop' -querytimeout 30 | |
| write-host ($tables | Format-List | Out-String) | |
| } | |
| } else { | |
| $scripts = Get-ChildItem $Scriptpath | Where-Object {$_.Extension -eq ".sql"} | |
| foreach ($s in $scripts) | |
| { Write-Host "Running Script : " $s.Name -BackgroundColor green -ForegroundColor darkRed | |
| $tables=Invoke-Sqlcmd -ServerInstance $Server -Username $UserName -Password $Password -Database $Database -InputFile $s.FullName -ErrorAction 'Stop' -querytimeout 30 | |
| write-host ($tables | Format-List | Out-String) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment