不知道为什么system.management.automation.dll存放在一个隐藏文件夹里面,入下图,我把他拷贝到项目的ThirdParty目录下。
在项目目录选择对该DLL的引用。
添加命名空间
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Collections.ObjectModel;
封装调用过程
private void RunPowershell(string filePath, string parameters)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command(filePath);
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
foreach (var parameter in parameters.Split(' '))
{
CommandParameter commandParm = new CommandParameter(null, parameter);
commandParameters.Add(commandParm);
scriptCommand.Parameters.Add(commandParm);
}
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
}
客户端代码
RunPowershell(@".\x.ps1", "");
本文转自Jake Lin博客园博客,原文链接:http://www.cnblogs.com/procoder/archive/2010/08/30/WPF-invoke-powershell.html,如需转载请自行联系原作者