【发布时间】: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 {<# exchange cmdlet invocations go here #>} -
@MathiasR.Jessen 真的,非常感谢!
标签: powershell powershell-remoting winrm