Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke-SqlCmd with either Windows Authentication OR SQL Authentication

This code does what I need. But I am trying to replace a call to Invoke-SqlCmd with either Windows Authentication or SQL Authentication on the same line using some kind of switch. Can someone help me with a more elegant way? I was thinking about Invoke-Expression but I don't get any good result out of it.

Function MyFunction{
    Param
    (
        [string]$S = "MyServer",
        [string]$U,
        [string]$P
    )
    # Find the SQL Engine version
    $Q = "select serverproperty('ProductVersion')"

    if($U)
    {
        $R = Invoke-Sqlcmd -ServerInstance $S -Query $Q -Username $U -Password $P -Verbose
        Write-Host "SQL Athenticated"
    }
    else
    {
        $R = Invoke-Sqlcmd -ServerInstance $S -Query $Q -Verbose
        Write-Host "Windows Athenticated"
    }
    return $R.column1
}

Here is my Invoke-Expression. It just doesn't work...

Invoke-Expression "$R = Invoke-Sqlcmd -ServerInstance $S -Query $Q $(if($true){""-Username $U -Password $P""})"

Here is the elegant solution I was looking for. Thanks to Mike:

Function MyFunction{
    Param
    (
        [string]$S = "xps15",
        [string]$U,
        [string]$P
    )
    # Find the SQL Engine version
    $Q = "select serverproperty('ProductVersion')"
    $auth=@{}
    if($U){$auth=@{UserName=$U;Password=$P}}
    $R = Invoke-Sqlcmd -ServerInstance $S -Query $Q -Verbose @Auth
    return $R.column1
}
like image 981
PollusB Avatar asked Sep 17 '25 19:09

PollusB


1 Answers

In my opinion the best solution here is called splatting (really). You build a hashtable with a set of parameters (potentially empty) and then use the splat operator (@) to present those arguments to the cmdlet.:

Function MyFunction{
    Param
    (
        [string]$S = "MyServer",
        [string]$U,
        [string]$P
    )
    # Find the SQL Engine version
    $Q = "select serverproperty('ProductVersion')"

    if($U)
    {
        $auth=@{UserName=$u;Password=$p}
        Write-Host "SQL Authenticated"
    }
    else
    {
    $auth=@{}
        Write-Host "Windows Authenticated"
    }
    $R = Invoke-Sqlcmd -ServerInstance $S -Query $Q -Verbose @Auth
    return $R.column1
}

See get-help about_splatting for more information.

like image 112
Mike Shepard Avatar answered Sep 21 '25 07:09

Mike Shepard