在WPF(C#)中调用PowerShell的脚本

添加对system.management.automation.dll的引用


不知道为什么system.management.automation.dll存放在一个隐藏文件夹里面,入下图,我把他拷贝到项目的ThirdParty目录下。

 

image

在项目目录选择对该DLL的引用。

image

 

添加命名空间

 

 

 

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", "");

需要注意还是需要使用.\来调用脚本.

posted @ 2010-08-30 06:37  Jake Lin  阅读(3631)  评论(3编辑  收藏  举报