powershell script query mssql windows authentication

Solutions on MaxInterview for powershell script query mssql windows authentication by the best coders in the world

showing results for - "powershell script query mssql windows authentication"
Ian
31 Feb 2018
1function global:SelectAllUsers()
2{
3    Read-Query -ConnectionString 'Server=localhost;Database=Ulysses;UID=EMEA\XJ193;PWD=somepassword;Integrated Security=true;' `
4        -Query "SELECT * FROM Users" `
5        -Action {
6            echo "I can take an action here"
7        }
8}
9
10function Read-Query
11{
12    param (
13        [Parameter(Mandatory=$true)]
14        [string]$ConnectionString,
15
16        [Parameter(Mandatory=$true)]
17        [string]$Query,
18
19        [Parameter(Mandatory=$true)]
20        [scriptblock]$Action
21    )
22
23    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
24    $SqlConnection.ConnectionString = $ConnectionString
25    $SqlConnection.Open()
26    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
27    $SqlCmd.CommandText = $Query
28    $SqlCmd.Connection = $SqlConnection
29    $reader = $SqlCmd.ExecuteReader()
30
31    while ($reader.Read())
32    {
33        $x = $null
34        $x = @{}
35
36        for ($i = 0; $i -lt $reader.FieldCount; ++$i)
37        {
38            $x.add($reader.GetName($i), $reader[$i])
39        }
40
41        Invoke-Command -ScriptBlock $action -ArgumentList $x
42    }
43
44    $SqlConnection.Close()
45}
46
47
48
49SelectAllUsers
50
similar questions