C#調用PowerShell的經歷


好久沒有寫程序了, 再次上手也處於功能強大的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這段程序了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM