/
authenticated_query.ps1.erb
48 lines (47 loc) · 1.77 KB
/
authenticated_query.ps1.erb
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
$json = cat '<%= @sql_instance_config %>' | ConvertFrom-Json
$env:SQLCMDUSER = $json.admin
$env:SQLCMDPASSWORD = $json.pass
if($json.instance -ne 'MSSQLSERVER'){
$env:SQLCMDSERVER = "localhost\${json.instance}"
}
try {
if (!(Get-Command 'sqlcmd.exe' -ErrorAction SilentlyContinue)){
if (Test-Path 'C:\Program Files\Microsoft SQL Server\120\Tools\Binn\sqlcmd.exe'){
$env:Path += ";C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;"
}elseif(Test-Path 'C:\Program Files\Microsoft SQL Server\110\Tools\Binn\sqlcmd.exe'){
$env:Path += ";C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;"
}else{
$result = ls 'C:\Program Files\Microsoft SQL Server' -Filter sqlcmd.exe -Recurse | Select -First 1
if ($result -eq $null) {
Write-Error -Message "Unable to find the sqlcmd.exe" -Category ResourceUnavailable
}else{
$env:Path += ";{0}" -f $result.DirectoryName
}
}
if (!(Get-Command 'sqlcmd.exe')){
Write-Error -Message "Unable to still find the sqlcmd.exe command" -Category ResourceUnavailable
}
}
$result = sqlcmd.exe -i '<%= input_file %>' -h-1 -W -s ',' <% if @instance != 'MSSQLSERVER' %>-S localhost\<%= @instance %><%end%>
if($result -match "THROW CAUGHT"){
Write-Host ($result | where {$_ -match "THROW CAUGHT"} | select -First 1)
Write-Error -Message ($result | where {$_ -match "THROW CAUGHT"} | select -First 1)
exit(10)
}
if($result -match "Incorrect syntax near "){
Write-Host ($result | where {$_ -match "Incorrect syntax near"} | select -First 1)
Write-Error -Message ($result | where {$_ -match "Incorrect syntax"} | select -First 1)
exit(10)
}
if($result -match "Msg \d+, Level 16"){
$msg = $result -join ' '
Write-Host $msg
Write-Error -Message "ERROR: $msg"
exit(10)
}
}
catch{
Write-Host $_
exit(20)
}
exit(0)