2

I'm new to PowerShell and I'm trying to convert the following line to C# code:

return -not (-not (Get-User $User -Company $Company -GroupName:$GroupName -AsJob | Wait-Job | %{ $_ | Receive-Job -ErrorAction SilentlyContinue; $_ | Remove-Job; }).ExternalUserId);

The above is pretty complex, so for now I'm just trying to convert this sub-portion of the above to C# code:

Get-User $User -Company $Company -GroupName:$GroupName -AsJob | Wait-Job | %{ $_ | Receive-Job -ErrorAction SilentlyContinue; $_ | Remove-Job; }

So far the code I have is this:

using (var psShell = PowerShell.Create())
            {
                using (var remoteRunspace = RunspaceFactory.CreateRunspace(CreateSession()))
                {
                    remoteRunspace.Open();
                    psShell.Runspace = remoteRunspace;

                    PSCommand command = new PSCommand();

                    command.AddCommand("Get-User")
                        .AddArgument("someUser")
                        .AddParameter("Company", "someCompany")
                        .AddParameter("GroupName:someGroupName")
                        .AddParameter("AsJob");

                    command.AddCommand("Wait-Job");

                    ///Need to add code for third pipelined command here

                    psShell.AddCommand(command);
                    psShell.Invoke();
                    command.Clear();

                }
            }

As you can see, I have only converted the first two pipelined commands into C#. I simply don't know how to convert the last one and add it to the above code, namely this one:

%{ $_ | Receive-Job -ErrorAction SilentlyContinue; $_ | Remove-Job; }

I know % is same as ForEach-Object and $_ is same as $PSItem, but still I don't know how to add a for loop inside a set of piped C# powershell commands.

Can someone help ?

Ahmad
  • 12,886
  • 30
  • 93
  • 146
  • As a general pointer: you can use the `.AddScript()` SDK method to execute pieces of PowerShell code as-is. More specifically: given the _synchronous_ use of jobs, why are jobs being used at all? – mklement0 Apr 01 '20 at 22:50
  • If your problem is the ForEach loop, please check this question https://stackoverflow.com/questions/7749221/c-sharp-powershell-pipeline-foreach-object – Mohamed Sahbi Apr 01 '20 at 23:08

0 Answers0