function INVOKE-SQL1:
functioninvoke-SQL {param([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 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}
function SQL2:
functionsql$sqlText,$database="Master",$server="."){ $connection= New-object System.Data.SqlClient.SQLConnection ("Data source= $server; Integrated security=sspi;initial catalog= $database"); $cmd= New-object System.Data.SqlClient.SqlCommand ($sqlText,$connection); $connection. Open (); $reader=$cmd. ExecuteReader ()$results= @() while($reader. Read ()) {$row= @{} for($i= 0;$i -lt $reader. FieldCount;$i++) { $row[$reader. GetName ($i)] =$reader. GetValue ($i) } $results+ = New-object Psobject-property$row } $connection. Close (); $results}
SQL Query3:
$ServerName="_servername_"$DatabaseName="_databasename_"$Query="SELECT * from Table WHERE Column = '"#Timeout Parameters$QueryTimeout= 120$ConnectionTimeout= 30#Action of connecting to the Database and executing the query and returning results if there were any.$conn=new-Object System.Data.SqlClient.SQLConnection$ConnectionString="server={0};D atabase={1};integrated security=true; Connect timeout={2}" - F $ServerName,$DatabaseName,$ConnectionTimeout$conn. connectionstring=$ConnectionString$conn. Open ()$cmd=new-object System. Data.SqlClient.SqlCommand ($Query,$conn)$cmd. commandtimeout=$QueryTimeout$ds=new-Object System. Data.dataset$da=new-object System. Data.SqlClient.SqlDataAdapter ($cmd) [void]$da. Fill ($ds)$conn. Close ()$ds. Tables
From:http://stackoverflow.com/questions/8423541/how-do-you-run-a-sql-server-query-from-powershell
PowerShell Query SQL Server