簡體   English   中英

如何在c#中添加Powershell SnapIn

[英]How to add Powershell SnapIn in c#

我有一個Powershell腳本,它存儲在一個名為“script”的字符串中,內容如下:

get-user |  out-file C:\Users\user\Desktop\user.txt -append

我的C#代碼:

RunspaceConfiguration runConfig = RunspaceConfiguration.Create();
                PSSnapInException psEx = null;
                runConfig.AddPSSnapIn("VMWare.View.Broker", out psEx);
                Runspace runspace = RunspaceFactory.CreateRunspace(runConfig);
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);
                Collection<PSObject> results = new Collection<PSObject>();
                results = pipeline.Invoke();
                runspace.Close();

如果我調試代碼,我會得到以下異常:

No snap-ins have been registered for Windows Powershell Version 2

如果我手動運行腳本並添加管理單元,它可以正常工作

該錯誤消息還意味着您正在嘗試從64位PowerShell實例加載32位管理單元(反之亦然。)在您的情況下,您需要編譯程序以定位正確的位數:x86。 AnyCPU將默認為您的機器的位數,即64位。

我有一個類似的問題...我試圖從控制台應用程序執行自定義PowerShell cmdlet。 我驗證我的控制台設置為4.0框架,powershell是3.0。 事實證明,控制台的bild選項卡中的“首選32位”設置問題設置為true。 我取消選中它,一切正常!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM