The function below can be used to a query to a database. The script returns any error as a result (2 lines).
function fnSQLCmd([string]$sInstance, [string]$sQuery, [string]$sDatabase) {
# Register SQPPS Module...
$oSQLPSModule = Get-Module | Where {$_.name -eq "SQLPS" }
if ($oSQLPSModule.Count -eq 0) {
Import-Module "SQLPS" -WarningAction SilentlyContinue
}
if ($sDatabase) {
[string]$sQuery = "Invoke-SqlCmd -ServerInstance " + $sInstance + " -Database " + $sDatabase + " -QueryTimeout 30 -Query `"" + $sQuery + "`" ; if (`$? -eq `$false) { @{`"ERROR0`" = `$error[0]}; @{`"ERROR1`" = `$error[1]} }"
} else {
[string]$sQuery = "Invoke-SqlCmd -ServerInstance " + $sInstance + " -QueryTimeout 30 -Query `"" + $sQuery + "`" ; if (`$? -eq `$false) { @{`"ERROR0`" = `$error[0]}; @{`"ERROR1`" = `$error[1]} }"
}
return Invoke-Expression $sQuery
}