TLDW: To support a specific process I need to go from a powershell instances/module to kick off a known safe executable for some c# magic, which then in turn needs to kick and execute a powershell script before exiting.
Powershell Entry point { Known Good Exe { Powershell Work To Do } }
Now ideally, this would all run from a single console instance so that all of the output is simple to look at. The exe -> powershell logging all works fine and as expected when using powershell.Streams.... The write-hosts in the powershell work all show up in the console and I get all the info I want.
powerShell.Streams.Information.DataAdded += LogMessage;
The problem comes when the outer powershell module is introduced. This one is needed because the parent process and execution environment this is running from is powershell. Once this whole stack is started from within a powershell instance, I get console logging from the outer powershell, and from the exe. BUT all of the write-hosts from the inner powershell modules disappear.
I've tried disabling the stream redirects, and a few other things, but this isn't resolving in the manner I would hope. I'm hoping someone knows if there is a way to get this to work as it solves so many problems if it just would.
PowerShell Outer:
$C#Exe = Join-Path $PSScriptRoot $C#ExePath
$C#Args = @()
Write-Host "Hello world" # will show up
& $C#Exe $C#Args
C# Exe Code:
public static void Main(string[] args)
{
Console.WriteLine("Hello world"); #Will show up
var powerShell = PowerShell.Create().AddScript("PowerShellInner.ps1");
powerShell.Streams.Information.DataAdded += LogMessage<InformationRecord>;
powerShell.Streams.Warning.DataAdded += LogMessage<WarningRecord>;
powerShell.Streams.Error.DataAdded += LogMessage<ErrorRecord>;
powerShell.Streams.Verbose.DataAdded += LogMessage<VerboseRecord>;
powerShell.Streams.Debug.DataAdded += LogMessage<DebugRecord>;
StringBuilder resultString = new StringBuilder();
foreach (dynamic item in powerShell.Invoke().ToList())
{
resultString.AppendLine(item.ToString());
}
Console.WriteLine(resultString.ToString());
}
private static void LogMessage<T>(object sender, DataAddedEventArgs e)
{
var data = (sender as PSDataCollection<T>)[e.Index];
Console.WriteLine($"[{typeof(T).Name}] {Convert.ToString(data)}");
}
PowerShell Inner:
Write-Host "Hello world" #Wont show up