【问题标题】:Powershell Pipe and Foreach-Object in c#C# 中的 Powershell 管道和 Foreach-Object
【发布时间】:2014-02-13 15:05:30
【问题描述】:

我正在调用 office365 的 get-msoluser cmdlet,并在 powershell 中使用以下 cmdlet

 Get-MsolUser -UserPrincipalName user@organization.onmicrosoft.com | ForEach-Object{ $_.licenses}

输出是许可证的集合,我希望在 c# 中运行相同的脚本。所以我写了如下代码

private void displayLicenses(){
     Command cmd = new Command("Get-MsolUser");
     cmd.Parameters.Add("UserPrincipalName","user@organization.onmicrosoft.com");
     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-Object' 未被识别为 cmdlet、函数的名称, 脚本文件或可运行的程序。检查名称的拼写,或 如果包含路径,请验证路径是否正确并尝试 再次。

我检查了我的项目是否引用了包含 ForEach-Object cmdlet 的 System.management.Automation.dll 文件。

我在 powershell 中找到了使用这个 cmd 的 dll

(Get-Command ForEach-Object).dll

谢谢, 萨提亚

【问题讨论】:

    标签: c# powershell foreach office365 powershell-remoting


    【解决方案1】:

    我找出了导致该问题的原因。这是由于我创建的运行空间配置错误。

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

    我正在创建一个空的初始状态,当我将其更改为默认状态时,它工作正常。在创建默认状态时,它包括默认获得的所有模块。

      InitialSessionState initalState = InitialSessionState.CreateDefault();
    

    效果很好。

    谢谢, 萨提亚

    【讨论】:

      【解决方案2】:

      听起来您正试图在 Exchange 服务器的远程会话中运行它。这些是 NoLanguage 受限会话,这意味着您只能在这些会话中运行 Exchange cmdlet。如果要使用 PowerShell 核心语言 cmdlet(如 foreach-object),则必须在本地会话中执行此操作,并使用 Import-PSSession 将 Exchange 函数导入本地会话(隐式远程处理),或使用 Invoke-Command并将其指向 Exchange 服务器上的远程会话。

      【讨论】:

      • 我正在执行 office365 cmdlet,并将 msonline 函数导入我的 office365 运行空间。
      猜你喜欢
      • 2011-12-06
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多