远程与会话
Enter-PSSession、Invoke-Command 概念。
30 分钟
远程与会话
PowerShell 远程 基于 WinRM(Windows Remote Management), cmdlet 如 Enter-PSSession、Invoke-Command。CodeRoadMap 生产跑 Linux SSH(linux-ssh);Windows 远程多用于域控、IIS 服务器或混合云。
学习目标
- 理解 WinRM 与 SSH 远程的区别
- 会用
Invoke-Command在远程机器执行脚本块 - 知道何时选 PowerShell 远程 vs Linux SSH
核心内容
WinRM 基础
# 客户端:测试连通(需目标已启用 WinRM)
Test-WSMan -ComputerName win-server.example.com
# 交互式远程 Shell(类似 ssh)
Enter-PSSession -ComputerName win-server.example.com -Credential (Get-Credential)
首次连接可能提示信任主机;生产环境应配置 HTTPS WinRM 与证书。
Invoke-Command
$scriptBlock = {
Get-NetTCPConnection -LocalPort 8080 -State Listen -ErrorAction SilentlyContinue
}
Invoke-Command -ComputerName win-server -ScriptBlock $scriptBlock -Credential $cred
-ScriptBlock 在 远程机器 执行;返回结果自动序列化为对象传回本地。
与 SSH 对照
| PowerShell 远程 | Linux SSH | |
|---|---|---|
| 协议 | WinRM (5985/5986) | SSH (22) |
| 入口 | Enter-PSSession | ssh user@host |
| 对象管道 | 支持(远程 cmdlet) | 纯文本 |
| 本站场景 | Windows Server 可选 | 主要生产环境 |
OpenSSH 也可在 Windows 上启用:ssh user@win-host,与 linux-ssh 命令一致。
会话与持久连接
$s = New-PSSession -ComputerName win-server -Credential $cred
Invoke-Command -Session $s -ScriptBlock { Get-Process java }
Remove-PSSession $s
New-PSSession 复用连接,批量命令比多次 Invoke-Command -ComputerName 更快。
安全注意
- 勿在脚本中硬编码密码;用
Get-Credential或 Secret Management - 远程执行等同于高权限操作,最小授权
- CodeRoadMap 部署优先 Git + CI(github-actions-essentials),减少交互式远程