Stack Exchange
C# - Powershell not returning anything from invoke-command if a pipe ( | ) is used
I have the following code to query remote servers and execute PowerShell cmdlets:
string query = ""; //I pass the powershell command here
InitialSessionState initial = InitialSessionState.CreateDefault();
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
string username = "" + Utilities.DC + "\\" + Utilities.getUsr();
Collection<PSObject> results;
PSCredential cred = new PSCredential(username, Utilities.getPass());
PowerShell account = PowerShell.Create();
account.Runspace = runspace;
ScriptBlock filter = ScriptBlock.Create(query);
account.AddCommand("Invoke-Command");
account.AddParameter("Credential", cred);
account.AddParameter("ComputerName", Utilities.Server);
account.AddParameter("ScriptBlock", filter);
results = account.Invoke();//Results obtained from the powershell query

If I pass a command like:
Get-ChildItem C:\Users -Directory

through the query string, I get the desired results back, however, If I have a more complex command with a pipe like:
Get-ChildItem C:\Users -Directory | ForEach-Object { Write-Host "test"}

I get zero results. If I paste the second command directly in PowerShell it works perfectly, the problem only shows up when I try to inject it through Invoke-Command within C#. Does anyone has an idea of what I might be doing wrong?
Edit: I searched around the forum before posting and could not find any duplicate of this question. After @PetSerAl commented with his response everything made sense and I was able to find many other questions that has a direct link to this one, but without knowing the answer first it was impossible to establish any sort of connection between them.

Write-Host do not return anything into successful stream. It writes on host and into information stream (PS v5.0+).

Simple but clever response. What you suggested makes total sense and I just proved it to be true by replacing Write-Host with Write-Output. Feel free to add your comment as an answer and I'll accept it.
