Powershell小技巧之使用WS-Man来调用PowerShell命令

2019-09-30 13:06:32丽君

该示例代码展示如何调用一个PowerShell 命令。它不使用任何WinRM的API,而是从模板创建必要的SOAP消息,并使用System.Net.HttpWebRequest将其通过网络发送。为了使用Windows中的示例代码,您需要启用WinRM服务配置基本身份验证(只适用于本地账号),您可以以管理员权限运行此PowerShell命令:


WinRSPsh http://server:5985/wsman user password "get-service"

如果你想让输出更加规范一点可以转换为为XML((.Net serialization):


WinRSPsh http://server:5985/wsman user password "(get-service ^| convertto-xml).OuterXml"

注意上面的例子中,你必须把管道字符转义,这样cmd.exe就不会去解释它了。