Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in SQL by (20.3k points)

Is there a way to execute an arbitrary query on a SQL Server using Powershell on my local machine?

1 Answer

0 votes
by (40.4k points)

If you want to run a SQL Server query from PowerShell with just stock .net and PowerShell (no additional SQL tools installed), use the function as follows:


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) $connection.Open()$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command

    $dataset = New-Object System.Data.DataSet

    $adapter.Fill($dataSet) | Out-Null




Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94.1k users

Browse Categories