5

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

0

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

The part regarding Windows authentication is not true. Quote from MSDN: If you specify both Integrated Security=true as well as a user name and password, the user name and password will be ignored and Windows authentication will be used. learn.microsoft.com/en-us/dotnet/framework/data/adonet/…
4

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).

1 Comment

Great article! But I spent a little time to understand how to correctly return the values from Get-DatabaseData in order to continue using this data. My edits at the end of the method: $dataset = New-Object -TypeName System.Data.DataSet $null = $adapter.Fill($dataset) $connection.Close() return Write-Output $dataset -NoEnumerate
0

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.

2 Comments

This does not seem to answer the question.
@TylerH added more info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.