【问题标题】:Powershell - Spawn a remote interactive shell from scriptPowershell - 从脚本生成远程交互式 shell
【发布时间】:2022-11-30 05:05:32
【问题描述】:

这是家庭作业的一部分。作为管理脚本的一部分,其中一项任务是使用脚本中的预设凭据在远程计算机上打开交互式 Powershell 提示符。从常规交互式 shell 打开一个工作正常,但是从脚本打开一个已被证明是困难的。

我尝试了以下方法:

$password = ConvertTo-SecureString -String "password" -AsPlainText -Force`
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "username", $password
$session = New-PSSession -Credential $credentials -ComputerName "remote-computer"
Enter-PSSession -Session $session

从交互式 shell 执行此操作按预期工作并在远程计算机上生成交互式提示,但是从脚本执行此操作会导致 shell 无响应,因为它需要脚本的进一步输入。

如果我在进入远程 Powershell 会话后尝试 Start-Process -Wait -NoNewWindow -FilePath "powershell" 或告诉 Start-Process 通过 cmd.exe 执行 Powershell,它会打开一个本地实例。

【问题讨论】:

    标签: powershell remote-access remote-server interactive-shell


    【解决方案1】:

    可能使用 -Session 和 -ScriptBlock 参数查看Invoke-Command。 您仍然会使用 PSSession 和 $Session 变量,但会将脚本块中的命令传递给该 PSSession。

    【讨论】:

    • 不幸的是,当尝试使用Start-Process 启动 shell 时,此方法似乎不起作用。它表现出与 OP 中描述的类似的“等待输入”行为。
    【解决方案2】:

    Invoke-Command 对我来说很好用:

    # Scriptblock to run in new Powershell process
    $cmd = {
        param(
            $targ,
            $user,
            $pass
        )
    
    $SecurePassword = ConvertTo-SecureString -String $pass -AsPlainText -Force -ErrorAction Stop
    $CredentialObj = New-Object System.Management.Automation.PSCredential($User,$SecurePassword) -ErrorAction Stop
    
    Enter-PSSession -ComputerName $targ -Credential $CredentialObj  | Invoke-Command -ScriptBlock {Set-Location -Path "C:."}
    
    }
    # Supply credentials and target
    $usertext = 'domainusername'
    $pwtext = 'mypassword'
    $Foundcomputer = 'targetcomputer'
    
    #Launch new Ps process and invoke scriptblock
    Start-Process powershell.exe -ArgumentList ("-noexit -command (Invoke-Command -ScriptBlock {$cmd} -ArgumentList $FoundComputer, " + $UserText + "," + $PwText + ")")
    

    【讨论】:

      猜你喜欢
      • 2010-09-11
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2015-06-29
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多