Abhaya Ghatkar
Abhaya Ghatkar

Reputation: 361

Powershell script to connect to sql db with windows authentication

What is the proper syntax to connect to a SQL server database using windows authentication?

Upvotes: 5

Views: 38607

Answers (3)

DRVR
DRVR

Reputation: 195

The Technet article at https://technet.microsoft.com/en-us/magazine/hh855069.aspx gives a great run-through of how to connect to a SQL Server database using PowerShell. It also includes an example function you can use in your scripts:

````powershell
function Get-DatabaseData {
    [CmdletBinding()]
    param (
        [string]$connectionString,
        [string]$query,
        [switch]$isSQLServer
    )
    if ($isSQLServer) {
        Write-Verbose 'in SQL Server mode'
        $connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
    } else {
        Write-Verbose 'in OleDB mode'
        $connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
    }
    $connection.ConnectionString = $connectionString
    $command = $connection.CreateCommand()
    $command.CommandText = $query
    if ($isSQLServer) {
        $adapter = New-Object-TypeName System.Data.SqlClient.SqlDataAdapter $command
    } else {
        $adapter = New-Object-TypeName System.Data.OleDb.OleDbDataAdapter $command
    }
    $dataset = New-Object -TypeName System.Data.DataSet
    $adapter.Fill($dataset)
    $dataset.Tables[0]
}
function Invoke-DatabaseQuery {
    [CmdletBinding()]
    param (
        [string]$connectionString,
        [string]$query,
        [switch]$isSQLServer
    )
    if ($isSQLServer) {
        Write-Verbose 'in SQL Server mode'
        $connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
    } else {
        Write-Verbose 'in OleDB mode'
        $connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
    }
    $connection.ConnectionString = $connectionString
    $command = $connection.CreateCommand()
    $command.CommandText = $query
    $connection.Open()
    $command.ExecuteNonQuery()
    $connection.close()
}
````

In the above script from the Technet article, you would just need to provide 3 parameters: the connection string (which you would use Trusted Connection=True for Integrated Security), the query to run and the type of DB (SQL Server or OleDB).

Upvotes: 4

DarkLite1
DarkLite1

Reputation: 14745

Additionaly, you can also revert to the function Invoke-Sqlcmd2 which automates all these things for you. We use it with great success and it makes life a lot easier.

The CmdLet Invoke-SqlCmd2 comes with the parameter Credential which can be omitted when using Windows Authentication.

.PARAMETER Credential
  Specifies A PSCredential for SQL Server Authentication connection to an instance of the Database Engine.
  If -Credential is not specified, Invoke-Sqlcmd attempts a Windows Authentication connection using the Windows account running the PowerShell session.

Upvotes: 0

draysams
draysams

Reputation: 1279

A normal SQL authentication connection string would look like

ConnectionString 'Server=$server;Database=$databaseName;UID=$DOMAIN\USER;PWD=$password'

The only main difference between the above and a windows authentication is by switching on Integrated Security

Integrated Security=true;

So a windows authentication connection string would read

ConnectionString 'Server=$server;Database=$databaseName;UID=$DOMAIN\USER;PWD=$password;Integrated Security=true;'

Note that it is optional to specify a domain for the UID if your server is localhost, thus you can simply specify UID as UID=sa;

Find below a complete code sample that can be adapted for your use case.

function global:SelectAllUsers()
{
    Read-Query -ConnectionString 'Server=localhost;Database=Ulysses;UID=EMEA\XJ193;PWD=somepassword;Integrated Security=true;' `
        -Query "SELECT * FROM Users" `
        -Action {
            echo "I can take an action here"
        }
}

function Read-Query
{
    param (
        [Parameter(Mandatory=$true)]
        [string]$ConnectionString,

        [Parameter(Mandatory=$true)]
        [string]$Query,

        [Parameter(Mandatory=$true)]
        [scriptblock]$Action
    )

    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = $ConnectionString
    $SqlConnection.Open()
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $Query
    $SqlCmd.Connection = $SqlConnection
    $reader = $SqlCmd.ExecuteReader()

    while ($reader.Read())
    {
        $x = $null
        $x = @{}

        for ($i = 0; $i -lt $reader.FieldCount; ++$i)
        {
            $x.add($reader.GetName($i), $reader[$i])
        }

        Invoke-Command -ScriptBlock $action -ArgumentList $x
    }

    $SqlConnection.Close()
}



SelectAllUsers

Upvotes: 4

Related Questions