C#调用PowerShell的经历

很久没有写程序了, 再次上手也处于功能强大的Windows PowerShell的缘故. 很少话, 先上段代码引入正题....shell

 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         }

编译开始后,反馈问题是缺乏 windows

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,这个能够经过以下命令检查:spa

.\Get-ExecutionPolicycode

这个状况在Windows 2008服务器也遇到并修改过。修改的方式是执行命令:blog

.\Set-ExecutionPolicy RemoteSignedip

但此次无效,缘由是注册表不被受权已PowerShell命令方式更改。 没辙只能手工进入注册表修改了 Computer\HKEY_LOCAL_MACHINE\SOFAWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\下ExecutionPolicy项的键值为"RemoteSigned" (注:这键值项多是不存在的,你能够建立它)。rem

完成这些后,就能够Run这段程序了。

相关文章
相关标签/搜索