For others who need to do this with just stock .net and PowerShell (no additional SQL tools installed) here is the function that I use:

function Invoke-SQL {
        [string] $dataSource = ".SQLEXPRESS",
        [string] $database = "MasterData",
        [string] $sqlCommand = $(throw "Please specify a query.")

    $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

    $connection = new-object$connectionString)
    $command = new-object$sqlCommand,$connection)

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null



I have been using this so long I don't know who wrote which parts but this was distilled from other's examples but simplified to be clear and just what is needed without extra dependencies or features.

I use and share this often enough that I have turned this into a script module on GitHub so that you can now go to your modules directory and execute git clone and from that point forward invoke-sql will automatically be loaded when you go to use it (assuming your using powershell v3 or later).

  • 0
Reply Report