代码之家  ›  专栏  ›  技术社区  ›  Kevin Ray

使用SQL Server帐户和加密密码连接到SQL Server并执行invoke sqlcmd

  •  0
  • Kevin Ray  · 技术社区  · 6 年前

    非常感谢你的帮助。我有一个PowerShell脚本,用于更新sqlserver表中的列。当它使用域帐户时,它可以正常工作。

    当key/txt文件使用域帐户时,没有问题。但当替换为SQL Server帐户详细信息时,则无法执行。

    $SQLUser = "Username"
    $SQLPasswordFile = "\\pathto\UserPW.txt"
    $SQLKeyFile = "\\pathto\UserPW.key"
    $SQLkey = Get-Content $SQLKeyFile
    $SQLMyCredential = New-Object -TypeName System.Management.Automation.PSCredential `
    -ArgumentList $SQLUser, (Get-Content $SQLPasswordFile | ConvertTo-SecureString -Key $SQLkey)
    $SQLCredentials = Get-Credential -Credential $SQLMyCredential
    $SQLSession = New-PSSession -ComputerName "uhpkpdb01" -Credential $SQLCredentials
    Invoke-Command -Session $SQLSession -ScriptBlock {
    $exist = Invoke-Sqlcmd "select count(1) from [table] where USER_NAME = '$($args[0])'" -ServerInstance "SERVERNAME"
    if ($exist.column1 -eq "1") {
    Invoke-Sqlcmd "UPDATE [table] SET PASSWORD = '$($args[1])' WHERE USER_NAME = '$($args[0])'"
    Write-Host "Account Updated"  }
    else {
    Write-Host "User Does Not Exists"}} -ArgumentList $env:USERNAME, "PASSWORD"
    Remove-PSSession $SQLSession
    

    New psesion:连接到远程服务器失败,原因是:用户名或密码不正确。

    我可以使用SQL Server帐户连接到SSMS并打开和更新表。 我一定是传错了用户名,但不知道该怎么做。

    1 回复  |  直到 6 年前
        1
  •  0
  •   user847990 user847990    6 年前

    你不能通过 PSCredential Invoke-Command . command唯一能理解的就是Windows凭据。

    你可以过去打电话给 Invoke-SqlCmd 如果您安装了模块,则直接从您自己的计算机发出命令。