-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExecuteSqlQuery.ps1
34 lines (29 loc) · 950 Bytes
/
ExecuteSqlQuery.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[CmdLetBinding(DefaultParameterSetName="File")]
param
(
[Parameter(Mandatory = $true)]
[string]$databaseName,
[string]$sqlServerName = "(localdb)\.",
[Parameter(Mandatory = $true, ParameterSetName="Query")]
[string]$sqlQuery,
[Parameter(Mandatory = $true, ParameterSetName="File")]
[string]$sqlFilePath
)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
try
{
$smoServer = new-object Microsoft.SqlServer.Management.Smo.Server($sqlServerName)
if(!$smoServer.Databases.Contains($databaseName))
{
Write-Error "Database $databaseName does not exist on $sqlServerName"
exit 1
}
$query = (((Get-Content $sqlFilePath) -join [Environment]::NewLine), $sqlQuery)[!$PSCmdlet.ParameterSetName -eq "File"]
$db = $smoServer.Databases[$databaseName]
$db.ExecuteNonQuery($query)
}
catch
{
Write-Error ($_ | Format-List * -Force | Out-String)
exit 1
}