Powershell 运行 管理员用户命令行

Powershell Running Command Line as Admin User

所以我有自动化功能,可以作为一个用户登录 Windows Server 2019 机器,但随后需要 运行 一个命令(Invoke-AdminCommand是特定于应用程序的,而不是内置的 Windows cmdlet)作为管理员用户(我不想将登录用户添加为管理员)。我遵循了此处的答案(如果您认为这是一个重复的问题)并且 none 有效。在脚本中,我执行“whoami”以确保会话是正确的用户,确实如此。但是命令 returns 一个特定于应用程序的错误表明用户没有正确的权限。如果我将 RDP 连接到与管理员用户相同的机器并通过 Powershell CLI 运行 相同的命令 - 它工作正常。

$username = "domain\adminUser"
$password = "**********" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$s = New-PSSession -credential $cred
$sc = {
    whoami
    Invoke-AdminCommand -Register -Verbose
}
Invoke-Command -Session $s -Scriptblock $sc
Remove-PSSession $s

您可能遇到了双跳问题。您正在远程连接到另一台服务器以 [​​=75=] 另一个本身需要身份验证的命令。如果您不能依靠 CredSSP(安全风险)或适当的帐户委托(维持大量委托可能会产生很高的开销,但这是解决问题的正确方法)。

Note: Basic auth will also work around this issue but I highly highly highly do not recommend using basic auth without at least setting up WinRM over SSL and removing non-HTTPS WinRM listeners.

无论您是使用 Kerberos(没有适当的授权或 CredSSP)还是 NTLM(因为 NTLM 无法转发令牌)作为身份验证方案,您都可以通过传递凭据信息到 Invoke-Command 并在该脚本块中构建凭据,并使用 Start-Process 以不同的用户身份启动它。请注意,如果您需要提升 UAC,代码会有所不同,并且此代码仅在您 不需要 需要 UAC 海拔:

# We will create the SecureString inside the Invoke-Command block
$password = "********"

# Use of a Disctionary instead of positional arguments and `param` in the block
# is a little trick you can use here.
Invoke-Command -Session $s -ArgumentList @{ Username = $username; Password = $password } {
  $cred =
    [PSCredential]::new($args.Username, ( $args.Password | ConvertTo-SecureString -AsPlainText -Force ))

  # Placeholder for next part
}

这就是您想要的样板。您将凭据发送到远程服务器并在那里构建它。你如何在 # Placeholder for next part 执行此操作将取决于你的确切身份 运行ning:

  • 外部命令(可执行)

    • 使用Start-Process到运行作为其他用户的程序
    Start-Process -Wait -Credential $cred program.exe -ArgumentList "arguments to the program here"
    
  • 任何接受 -Credential 参数的 cmdlet 或任何接受用户名和密码参数的命令

    • 将凭据参数直接传递给 cmdlet/function,或将 $args.Username$args.Password 直接传递给具有 username/password 参数的外部命令。然而,下面举例说明了将其与 cmdlet 和 -Credential 参数一起使用。
    # Note that some cmdlets don't take a credential for whatever reason
    # and may have -Username and -Password arguments instead.
    Invoke-AdminCommand -Credential $cred -Register -Verbose
    
  • 任何不接受 -Credential 参数或 username/password 参数的函数或 Cmdlet

    • 这与第一个示例类似,但此示例专门针对 运行将一些 PowerShell 代码作为您想要的代码的另一个用户。
    # This can be invoked without splatting but am using splatting for readability
    $spArgs = @{
      Credential = $cred
      FilePath = 'powershell.exe' # You can use `pwsh.exe` for PS Core if necessary
      ArgumentList = "-Command ""exampleProgram.exe -username $($args.Username) -password $($args.Password)"""
      Wait = $true
      NoNewWindow = $true
    }
    Start-Process powershell.exe