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 ?