我在http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/上有一篇文章描述了一种通过 WinRM 从 .NET 运行 Powershell 的简单方法。
如果您只想复制代码,则该代码位于单个文件中,它也是一个 NuGet 包,其中包含对 System.Management.Automation 的引用。
它自动管理受信任的主机,可以运行脚本块,还可以发送文件(这并不真正受支持,但我创建了一个解决方法)。返回的总是来自 Powershell 的原始对象。
// this is the entrypoint to interact with the system (interfaced for testing).
var machineManager = new MachineManager(
"10.0.0.1",
"Administrator",
MachineManager.ConvertStringToSecureString("xxx"),
true);
// will perform a user initiated reboot.
machineManager.Reboot();
// can run random script blocks WITH parameters.
var fileObjects = machineManager.RunScript(
"{ param($path) ls $path }",
new[] { @"C:\PathToList" });
// can transfer files to the remote server (over WinRM's protocol!).
var localFilePath = @"D:\Temp\BigFileLocal.nupkg";
var fileBytes = File.ReadAllBytes(localFilePath);
var remoteFilePath = @"D:\Temp\BigFileRemote.nupkg";
machineManager.SendFile(remoteFilePath, fileBytes);
如果这有帮助,请标记为答案。我已经在我的自动化部署中使用了一段时间。如果您发现问题,请发表评论。