Simple SQL Abfragen in PowerShell

Mit Hilfe dieser kleine PowerShell Funktion, die die SQL Client Funktionalität des .NET Frameworks nutzt, lassen sich in PowerShell einfache SQL Abfragen bewerkstelligen, ohne das z.B. das SQL Server Modul benötigt wird

function Invoke-SQL {
    Param(
        [string]$DataSource,
        [string]$Database,
        [string]$SqlCommand,
        [string]$User,
        [string]$Password
    )
    if (($User) -and ($Password)) {
        $connectionString = "Data Source=$dataSource;User ID=$User;Password=$Password;Initial Catalog=$Database"
    } else { 
        $connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Initial Catalog=$database"
     }
    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $connection.Open()
    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null
    $connection.Close()
    $dataSet.Tables
}
# Example usage (sql auth):
Invoke-SQL -dataSource 192.168.178.100 -database Master -user sa -password Geheim -sqlCommand 'Select * from sysdatabases'

# Example usage (Integrated auth):
Invoke-SQL -dataSource 192.168.178.100 -database Master -sqlCommand 'Select * from sysdatabases'

2 Kommentare

  1. Servus,
    Vielen Dank für die Informationen / das Skript.
    Funktioniert es auch, wenn man die Query um eine where Klausel erweitert?
    Bei mir tritt leider ein Fehler auf.

Schreibe einen Kommentar zu Andreas Mariotti Abbrechen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert