【问题标题】:Re-using PowerShell session with WinRM通过 WinRM 重新使用 PowerShell 会话
【发布时间】:2021-12-02 23:07:53
【问题描述】:

我的总体目标是初始化一次 powershell 会话,随着时间的推移调用一些命令,最后关闭会话。我需要通过 winrm 调用 powershell。由于我正在开发Java应用程序,因此我使用winrm4j通过winrm调用shell命令。

保持 ps 会话打开的动机是我通过 Connect-ExchangeOnline cmdlet 访问 Exchange Online。不幸的是,这大约需要 10 秒,为了节省时间,我想在 Get-Mailbox 等多个命令中重复使用 ps 会话,而不是每次调用 Exchange cmdlet 时都连接到 Exchange Online。

这是我正在执行的伪 powershell 代码。现在,我在本地机器上运行:

  • 开始会话:
$s = New-PSSession -Name mysession -ComputerName . -Authentication Basic -Credential ...
Invoke-Command -Session $s -ScriptBlock { <# here comes Exchange online initialization #> }
Disconnect-PSSession -Session $s
  • 调用命令:
$rs = Get-PSSession -Name mysession -ComputerName . -Authentication Basic -Credential ...
Connect-PSSession -Session $s
Enter-PSSession -Session $s
<# run the actual Exchange cmdlet #>
Exit-PSSession
Disconnect-PSSession -Session $s
  • 清理:
$rs = Get-PSSession -Name mysession -ComputerName . -Authentication Basic -Credential ...
Remove-PSSession -Session $rs

当我手动执行此操作时,我可以运行 Get-Mailbox 并获得正确的结果。 但是,当我以编程方式运行它时,它不起作用。返回一个错误,指出无法以 cmdlet 找到 Get-Mailbox。以及其他变量从初始化或不可用。

通过 winrm 有什么不同?

【问题讨论】:

  • Enter-PSSession 仅用于交互式使用 - 对于无人值守脚本,请使用Invoke-Command -Session $s -ScriptBlock {&lt;# exchange cmdlet invocations go here #&gt;}
  • @MathiasR.Jessen 真的,非常感谢!

标签: powershell powershell-remoting winrm


【解决方案1】:

正如 Mathias 在 cmets 中指出的那样,解决方案是使用 Invoke-Command 而不是 Enter-PSSession,因为它仅用于交互式会话。不幸的是,以编程方式通过 winrm 调用 Enter-PSSession 时没有错误消息或类似信息。

【讨论】:

    猜你喜欢
    • 2019-05-02
    • 2020-01-07
    • 2014-01-16
    • 1970-01-01
    • 2011-06-10
    • 2020-12-02
    • 2022-08-16
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多