【问题标题】:Run Invoke-Command in remote computer as administrator以管理员身份在远程计算机上运行 Invoke-Command
【发布时间】:2020-11-27 00:31:11
【问题描述】:

我正在尝试运行 invoke-command 以在 remote computer 上启动 powershell script in a powershell file。我正在使用credentials for a user with Administrator privilege。该命令需要running powershell as an administrator执行。我尝试使用 powershell 脚本调用的应用程序存在许可问题,因此我无法将凭据更改为管理员,但需要与该特定用户本身一起运行。我曾尝试在 Invoke-Command 末尾使用 -RunAsAdministrator,但出现错误提示:

Invoke-Command : Parameter set cannot be resolved using the specified named parameters.

$command = {
    cd Folder
    C:\Folder\build.ps1
} 
Invoke-Command -ComputerName $RemoteSystemIP -ScriptBlock $command -credential $Credentials1 -ErrorAction Stop -AsJob

我正在尝试将此作为后台作业执行,这就是我添加-AsJob 参数的原因。

已经好几天了,我还没有找到解决办法。

【问题讨论】:

    标签: powershell invoke-command


    【解决方案1】:

    tl;dr

    • 让远程 PowerShell 会话执行提升权限(具有管理员权限)的唯一方法是连接到在目标计算机上具有管理员权限的用户帐户(隐式或通过 -Credential)。

    • 使用这样的帐户,会话会自动且始终以提升的方式运行。


    Invoke-Command-RunAsAdministrator 开关只能用于(虚拟化)容器-ContainerId 参数),不定期远程处理(-ComputerName 参数)。

    不能在远程会话中按需提升(您可以通过Start-Process -Verb RunAs本地交互)。 [1]

    相反,您必须确保您传递给Invoke-Command -Credential 的凭据 以连接到远程计算机,并引用一个(也)具有管理权限的用户帐户目标机器,在这种情况下,远程会话自动且始终运行提升(具有管理员权限)。

    如果您无法通过此类凭据,我认为您不走运。


    测试当前用户是否具有管理权限

    # Returns $true if elevated, otherwise $false.
    [Security.Principal.WindowsPrincipal]::new(
      [Security.Principal.WindowsIdentity]::GetCurrent()
    ).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
    

    一个利用net session的简单快捷方式只有在提升时才会成功:

    # Returns $true if elevated, otherwise $false.
    [bool] (net session 2>$null)
    

    [1] 除非会话已经提升,否则-Verb RunAs 会弹出一个用户必须以交互方式确认的 UAC 对话框,远程会话不支持该对话框。

    【讨论】:

      【解决方案2】:

      我认为你应该这样做:

      $command = {
          Start-Process "powershell" -Verb runas -Workingdirectory "C:\Folder\" -ArgumentList "build.ps1"
      }
      
      Invoke-Command -ComputerName $RemoteSystemIP -ScriptBlock $command -credential $Credentials1 -ErrorAction Stop -AsJob
      

      【讨论】:

      • 它没有在 build.ps1 中执行脚本
      • 如果凭据是管理员凭据,远程会话会自动提升 - 无需额外工作;如果不是,尝试使用 Start-Process -Verb RunAs 按需提升是否 工作(无法显示 UAC GUI)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 2011-02-18
      • 1970-01-01
      • 2020-11-20
      • 2023-01-24
      • 2013-10-07
      • 1970-01-01
      相关资源
      最近更新 更多