在提升的会话中使用 Invoke-Command 运行 启动进程

Using Invoke-Command to run Start-Process in an elevated session

作为在多个远程服务器上 运行 安装文件的先驱,我需要更新 Powershell 设置 MaxMemoryPerShellMB。这需要在远程服务器上以管理员身份 运行 建立一个 PS 会话。我一直在尝试 运行 Invoke-Command 然后 运行 一个 ScriptBlock 由 Start-Process 命令组成,其中包括 -Verb RunAs 参数。然而,似乎没有任何效果。

我尝试过各种引用方案,单引号、双引号、三引号,但似乎没有任何效果。

我已经尝试 运行从 Enter-PSSession 中选择 Start-Process,结果相同。

以下是我正在测试的代码:

$creds = Get-Credential -Username 'DOMAIN\userID' -Message "Enter Username and Password to access the remote servers."

$ScriptBlock = {
    Start-Process -FilePath Powershell.exe -ArgumentList """Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024""" -Verb RunAs -Wait 
}
Invoke-Command -ComputerName testsvr01 -Credential $creds -ScriptBlock $ScriptBlock

我应该可以通过 RDP 连接到远程服务器和 运行 Get-Item WSMan:\localhost\Shell 并让它显示更新后的值,但值没有改变。

当 运行 在 Invoke-Command 运行 时暂停代码,但除此之外,Powershell 中没有反馈。

在远程服务器上,我在系统事件日志中看到以下两个 Kerberos 错误。

0x19 KDC_ERR_PREAUTH_REQUIRED,

0xd KDC_ERR_BADOPTION

非常感谢任何帮助。

> powershell.exe -?
...
EXAMPLES
...
PowerShell -Command "& {Get-EventLog -LogName security}"

-Command
...
 To write a string that runs a Windows PowerShell command, use the format:
    "& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.

因此您可以尝试通过以下方式调用 Set-Item

$ScriptBlock = {
    Start-Process -FilePath Powershell.exe -ArgumentList "-Command"," &{ Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024 }" -Verb RunAs -Wait -PassThru
}
$process = Invoke-Command -ComputerName testsvr01 -Credential $creds -ScriptBlock $ScriptBlock
$process.ExitCode

我还通过 -PassThru 返回了一个进程对象,您可以在其中检查 `ExitCode``

希望对您有所帮助