Search code examples
c#powershellforeachoffice365powershell-remoting

Powershell Pipe and Foreach-Object in c#


I am invoking a get-msoluser cmdlet of office365 and i use the following cmdlet in powershell

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

The output is a collection of licenses and i wanted the same script to be run in c#. so i have written the code as follows

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);
          }
     }
}

But i still get an error on executing this function saying

Unhandled Exception: System.Management.Automation.CommandNotFoundException: The term 'ForEach-Object' is not recognized as the name of a cmdlet, function, scrip t file, or operable program. Check the spelling of the name, or if a path was in cluded, verify that the path is correct and try again.

I checked that my project has a reference to System.management.Automation.dll file that contains the ForEach-Object cmdlet.

I found the dll using this cmd in powershell

(Get-Command ForEach-Object).dll

Thanks, Satya


Solution

  • I figured out the problem causing for the issue. It is due to the misconfigured runspace i created.

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

    i was creating the initalstate with empty one,When i changed it to default one it worked fine.On creating the default one it includes all the modules that were obtained by default.

      InitialSessionState initalState = InitialSessionState.CreateDefault();
    

    it worked fine.

    Thanks, Satya