【问题标题】:Invoke-SqlCmd with either Windows Authentication OR SQL Authentication使用 Windows 身份验证或 SQL 身份验证调用 SqlCmd
【发布时间】:2015-12-07 07:09:25
【问题描述】:

这段代码可以满足我的需要。但是我正在尝试使用某种开关在同一行上用 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
}

【问题讨论】:

  • 必须是单行解决方案吗? 2行呢?如果是这样,第一行会将变量设置为所需的凭据,第二行将是您的调用,利用第一行中的变量。我不是所有事情单行解决方案的最大粉丝,它会使阅读/解释变得更加困难。
  • 那么您问题中的哪些代码不起作用?顶部的代码块或末尾的 Invoke-Expression 位。如果是后者,那为什么还要提到第一个 blob? “它只是不起作用..” - 它以什么方式“不起作用?”,您是否收到任何错误消息,如果有,为什么不发布它们。如果你想让人们在这里帮助你,那么请学习如何提问,因为坦率地说,我不知道你在问什么:codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question - 请不要浪费我们的时间。
  • 这其实是个好问题。不想表达 Invoke-SQLCmd 两次是很自然的,而且有一个很好的 PowerShell 解决方案。

标签: sql-server powershell powershell-3.0


【解决方案1】:

在我看来,这里最好的解决方案是喷溅(真的)。您使用一组参数(可能为空)构建一个哈希表,然后使用 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

【讨论】:

  • 我希望我能多次投票赞成这个!
猜你喜欢
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多