Invoke-SQL
Description:
Function can be used to make SQL queries without installing SQL modules/SQL locally. I did not write this query, and I don't recall where I originally found it. I've used this a ton for several years, and I did add the encryption option to it at some point. Other than that I believe I left it pretty much as I found it.
Language:
PowerShell
Usage Type:
Standalone
Script Source:
function Invoke-SQL { param ( [string]$dataSource, [string]$database, [string]$sqlCommand = $(throw "Please specify a query.") ) if (Test-Connection -ComputerName $dataSource -Count 2 -Quiet) { $connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Encrypt=True;" + "TrustServerCertificate=True;" + "Initial Catalog=$database" $connection = new-object system.data.SqlClient.SQLConnection($connectionString) $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection) Try { $connection.Open() $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command $dataset = New-Object System.Data.DataSet $adapter.Fill($dataSet) | Out-Null $connection.Close() $Result = $dataSet.Tables } catch { $ErrorMessage = $PSItem.ToString() switch -Wildcard ($ErrorMessage) { "*Login failed for user*" { $ErrorParts = $ErrorMessage.split("`n") $UserName = $ErrorParts[1].Split("'")[1].Replace("'", "") $QueryError = "User ""$($UserName)"" failed to login to the database." } default { $QueryError = "Unhandled Error: $($ErrorMessage)" } } $Result = "Error: A query to database ""$($database)"" on host ""$($dataSource)"" failed." } } else { $Result = "Error: A query to the Database ""$($database)"" on host ""$($dataSource)"" was not attempted: $($dataSource) is unreachable." } return $Result }
Note: that all applications posted here are posted for use, both commercial and non-commercial, free of charge, and as such are provided as-is, without warranty of any kind whatsoever. visuaFUSION, FMSCUG or any other program listed here's author are not responsible for any damages or shortcomings that result from usage of any of these applications.