使用 Windows 身份验证或 SQL 身份验证调用 SqlCmd

Invoke-SqlCmd with either Windows Authentication OR SQL Authentication

这段代码可以满足我的需要。但我正在尝试使用某种开关在同一行上用 Windows 身份验证或 SQL 身份验证替换对 Invoke-SqlCmd 的调用。有人可以用更优雅的方式帮助我吗?我在考虑 Invoke-Expression,但没有得到任何好的结果。

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
}

这是我的调用表达式。就是不行...

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

这是我一直在寻找的优雅解决方案。感谢迈克:

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
}

在我看来,这里最好的解决方案称为 splatting(真的)。您使用一组参数(可能为空)构建哈希表,然后使用 splat 运算符 (@) 将这些参数呈现给 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
}

有关详细信息,请参阅 get-help about_splatting