好久没有写程序了, 再次上手也处于功能强大的Windows PowerShell的缘故. 不多话, 先上段代码引入正题....
1 static Collection<PSObject> RunPowershell(string filePath, string parameters) 2 { 3 RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); 4 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); 5 runspace.Open(); 6 RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 7 Pipeline pipeline = runspace.CreatePipeline(); 8 Command scriptCommand = new Command(filePath); 9 Collection<CommandParameter> commandParameters = new Collection<CommandParameter>(); 10 foreach (var parameter in parameters.Split(' ')) 11 { 12 CommandParameter commandParm = new CommandParameter(null, parameter); 13 commandParameters.Add(commandParm); 14 scriptCommand.Parameters.Add(commandParm); 15 } 16 pipeline.Commands.Add(scriptCommand); 17 Collection<PSObject> psObjects; 18 psObjects = pipeline.Invoke(); 19 if (pipeline.Error.Count > 0) 20 { 21 throw new Exception("Something is wrong in PowerShell script."); 22 } 23 24 runspace.Close(); 25 26 return psObjects; 27 }
编译开始后,反馈问题是缺少
using System.Management.Automation;
using System.Management.Automation.Runspaces;
的引用。 baidu查看很多都是提到要安装SDK之类的。考虑当前用的编辑器就是Visual Studio 2013 Premium,思考应该已经包含这个DLL了吧。
其实它就在系统目录下的,参考C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35目录下,这个是windows 7 Pro 64bit的存放位置。
编译通过后测试运行,而抛出一个程序异常错误信息,错误停留在上述第18行代码处。经过一番检查后发现问题是,本机PowerShell的ExecutionPolicy是Restricted,这个可以通过如下命令检查:
.\Get-ExecutionPolicy
这个情况在Windows 2008服务器也遇到并修改过。修改的方式是执行命令:
.\Set-ExecutionPolicy RemoteSigned
但这次无效,原因是注册表不被授权已PowerShell命令方式更改。 没辙只能手工进入注册表修改了 Computer\HKEY_LOCAL_MACHINE\SOFAWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\下ExecutionPolicy项的键值为"RemoteSigned" (注:这键值项可能是不存在的,你可以创建它)。
完成这些后,就可以Run这段程序了。