Etaila
Etaila

Reputation: 208

Clear Powershell Streams in C#

I have 3 commands for powershell:

            shell.AddScript("Exit-PSSession");
            shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {some command}");
            shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {another command}");

Now I don't need any response from the first two, but I need the error log from the third one. Because I can't foresee how many errors may occur, I want to clear the shell from at least all error messages, better would be a complete empty shell.

My solution was this:

            shell.AddScript("Exit-PSSession");
            shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {some command}");
            shell.Invoke();
            shell.Streams.ClearStreams();
            shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {another command}");

But somehow ClearStreams does nothing at all, shell still knows all old errors and the two previous commands.

The Microsoft sides don't give any more informati0on, than that this method exists and should clear out the shell. (Microsoft Help for ClearStreams) or Microsoft Help for streams in general

Did I miss something, or am I misunderstanding what they

(Powershell is Version 5.0) and C# runs 4.6 NET Framework

Thanks for help in advance.

Upvotes: 1

Views: 3165

Answers (1)

Ranadip Dutta
Ranadip Dutta

Reputation: 9341

you can use this:

powershell.Streams.Error();

Sample:

PowerShell powershell = PowerShell.Create();
powershell.Runspace = CreateRunSpace.runspace;
var exec = "Set-Mailbox -Identity John -DeliverToMailboxAndForward $true -ForwardingSMTPAddress '[email protected]'";
powershell.AddScript(exec);
powershell.Streams.Error.Clear();
powershell.Streams.Warning.Clear();
var result = powershell.Invoke();
MessageBox.Show(powershell.Streams.Error.Count().ToString()+" error counts");

foreach (var errorRecord in powershell.Streams.Error)
{
MessageBox.Show(errorRecord.ToString()+"first - error");
}

Requesting you to post the full script. What kind of object shell is. I think it will have a method as .Clear()

NOte: I got this :

sh.Commands.AddScript("Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager"); sh.Invoke(); sh.Commands.Clear();

Could you please check that

Upvotes: 3

Related Questions