上一节,我们简单介绍了,PowerShell远程管理所依赖的三个服务。这一节我们来学习下PowerShell远程管理的几种方式。
上一节:PowerShell远程管理01——Powershell远程管理依赖的服务及配置
Powershell应该有五种远程管理的方式
分别是:
使用交互式会话
使用远程执行命令 (Invoke-command -ScriptBlock {})
使用远程运行脚本(Invoke-command -FilePath )
建立持久连接 (New-PSSession)
其他支持远程执行的命令( [-ComputerName ])
1、使用交互式会话
使用“Enter-PSSession RemoteComputer”启动一个交互式会话,然后可以在会话中执行Powershell命令,如同在此服务本地执行Powershell一样。
# 基本结构如下
Enter-PSSession -Credential $Credential
Exit-PSSession
实际操作记录如下:
PS C:\> Enter-PSSession -ComputerName "sz-test1119.test.local"
[sz-test1119.test.local]: PS C:\Users\xxx\Documents>
[sz-test1119.test.local]: PS C:\Users\xxx\Documents> cd c:\
[sz-test1119.test.local]: PS C:\>
[sz-test1119.test.local]: PS C:\>
[sz-test1119.test.local]: PS C:\> Get-Service "winrm"
Status Name DisplayName
------ ---- -----------
Running winrm Windows Remote Management (WS-Manag...
[sz-test1119.test.local]: PS C:\> Exit-PSSession
2、使用远程执行命令 (Invoke-command -ScriptBlock {})
借助于“Invoke-command”的“-ComputerName”参数和“-ScriptBlock”参数直接在本地写Powershell命令块在远程服务器执行.
# 基本命令结构
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock {Get-UICulture} -Credential $Credential
PS C:\> Invoke-Command -Credential $cred -ComputerName "sz-test1122.test.local"