2011-09-27 59 views
0

如果我嘗試通過c#運行Powershell命令,我得到以下錯誤: 「術語'select'不被識別爲cmdlet函數的名稱,腳本文件或可操作程序,檢查名稱的拼寫,或者如果包含路徑,請驗證路徑是否正確,然後重試。使用文字和代碼塊與c#與PowerShell 2.0交互的問題

如果命令直接執行Powershell(.exe)一切正常!

我嘗試運行的命令看起來像IG: 「獲取郵箱 - 組織'CoolOrganizationNameGoesHere' |選擇ServerName

似乎有與「管」的問題|, 我已經浪費了時間上在主要搜索引擎搜索最瘋狂的關鍵字組合, ,但我沒有發現任何可行的。

我試過的最後一件事情是將IIS-ApplicationPSLanguageMode屬性設置爲Powershell,結果與前面寫的一樣。

也許有WinRM配置錯誤?或者我的本地Powershell配置已損壞? 是否有任何關於C#(或任何其他.Net語言)使用Powershell遠程訪問 以及使用Pipe | 「命令」?

有人可以告訴我什麼是錯,這就像在大海撈針!

謝謝!

+0

請發佈sampl e代碼完全展示了你如何試圖從C#調用Powershell腳本。 – paulsm4

回答

2

竅門可能是你創建你的命令的方式。如果你正在運行腳本作爲一個字符串,你應該使用:

Command myCommand = new Command(script, true); 

但是,如果你想運行它作爲一個文件名 - 你應該使用:

Command myCommand = new Command(script, false); 

所以:

Command myCommand = new Command("Get-Date", true); 
Command myCommand = new Command("c:\test.ps1", false); 

如果您需要完整的方法:

private static IEnumerable<PSObject> ExecutePowerShellScript(string script, bool isScript = false, IEnumerable<KeyValuePair<string, object>> parameters = null) 
{ 
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); 
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); 
    runspace.Open(); 

    Command myCommand = new Command(script, isScript); 
    if (parameters != null) 
     { 
      foreach (var parameter in parameters) 
      { 
       myCommand.Parameters.Add(new CommandParameter(parameter.Key, parameter.Value)); 
      } 
     } 
    Pipeline pipeline = runspace.CreatePipeline(); 

    pipeline.Commands.Add(myCommand); 
    var result = pipeline.Invoke(); 

    // Check for errors 
    if (pipeline.Error.Count > 0) 
     { 
      StringBuilder builder = new StringBuilder(); 
      //iterate over Error PipeLine until end 
      while (!pipeline.Error.EndOfPipeline) 
      { 
       //read one PSObject off the pipeline 
       var value = pipeline.Error.Read() as PSObject; 
       if (value != null) 
       { 
        //get the ErrorRecord 
        var r = value.BaseObject as ErrorRecord; 
        if (r != null) 
        { 
         //build whatever kind of message your want 
         builder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message); 
         builder.AppendLine(r.InvocationInfo.PositionMessage); 
         builder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo)); 
         builder.AppendLine(string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId)); 
        } 
       } 
      } 
      throw new Exception(builder.ToString()); 
     } 
    return result; 
}