2014-01-23 56 views
1

我調用的office365一個get-msoluser cmdlet的我用的是以下cmdlet在PowerShell中Powershell的管道和在C#中的foreach對象

Get-MsolUser -UserPrincipalName [email protected] | ForEach-Object{ $_.licenses} 

的輸出許可證的集合,我想同樣的腳本在C#中運行。所以我寫的代碼如下

private void displayLicenses(){ 
    Command cmd = new Command("Get-MsolUser"); 
    cmd.Parameters.Add("UserPrincipalName","[email protected]"); 
    Command cmd2 = new Command("ForEach-Object"); 
    cmd2.Parameters.Add("$_.licenses.AccountSku"); 
    Pipeline pipe = Office365Runspace.CreatePipeline(); 
    pipe.Commands.Add(cmd); 
    pipe.Commands.Add(cmd2); 
    Console.WriteLine("Before invoking the pipe"); 
    ICollection<PSObject> result = pipe.Invoke(); 
    CheckForErrors(pipe); 
    Console.WriteLine("Executed command {0} + {1} with no error", cmd.CommandText, cmd2.CommandText); 
     foreach(PSObject obj in result){ 
      foreach(PSPropertyInfo propInfo in obj.Properties){ 
       Console.WriteLine(propInfo.Name+": "+propInfo.Value+" "+propInfo.MemberType); 
      } 
    } 
} 

但是我還是在執行這個功能說

未處理的異常錯誤: System.Management.Automation.CommandNotFoundException:術語 「ForEach-對象'不被識別爲cmdlet,函數,腳本文件或可操作程序的名稱。檢查名稱的拼寫,如果包含路徑,請檢查路徑是否正確,然後再次嘗試 。

我檢查了我的項目有一個對包含ForEach-Object cmdlet的System.management.Automation.dll文件的引用。

我發現使用此CMD的dll在PowerShell中

(Get-Command ForEach-Object).dll 

感謝, 薩蒂亞

回答

1

我想出了導致問題的問題。這是由於我創建的配置不當的運行空間。

InitialSessionState initalState = InitialSessionState.Create(); 
    initalState.ImportPSModule(new String[] { "msonline" }); 
    //initalState.LanguageMode = PSLanguageMode.FullLanguage; 

    Office365Runspace = RunspaceFactory.CreateRunspace(initalState); 
    Office365Runspace.Open(); 

我創建空之一initalstate,當我改變爲默認一個它的工作fine.On創建缺省一個它包括由默認獲得了所有模塊。

InitialSessionState initalState = InitialSessionState.CreateDefault(); 

它工作正常。

感謝, 薩蒂亞

0

這聽起來像your're試圖運行在Exchange服務器的遠程會話。這些都是NoLanguage受限會話,這意味着您只能在這些會話中運行Exchange cmdlet。如果要使用PowerShell核心語言cmdlet(如foreach-object),則必須在本地會話中執行該操作,並使用Import-PSSession將Exchange函數導入本地會話(隱式遠程處理),或使用Invoke-Command並將其指向Exchange服務器上的遠程會話。

+0

我做office365 cmdlet,並我進口msonline功能,我的office365運行空間。 – satya