用 New-PSSession 复用远程连接

建立一个持久会话并在其上运行多条命令。

Windows网络系统性能管理员PowerShell低风险
运行 $s = New-PSSession -ComputerName 主机,之后给各命令传 -Session $s。

01命令

命令
$ $s = New-PSSession -ComputerName server01; Invoke-Command -Session $s -ScriptBlock { Get-Date }; Remove-PSSession $s

02作用说明

每次 Invoke-Command 通常都会开关连接,而具名 PSSession 只建立一次并复用,减少认证开销并保留已导入模块等状态。针对同一主机自动化多步操作时,持久会话必不可少。

03风险

风险低风险
使用条件Windows 10/11 with PowerShell 5.1 or PowerShell 7+
!注意: 空闲会话会在两端占用资源;脚本结束时用 Remove-PSSession 关闭。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • New-PSSession
    Microsoft Learn · vendor-doc · 2026-09-20
    依据: Creates a persistent connection to a local or remote computer.

最后验证: 2026-10-13 · 分类: 系统与设置

06相关方案