I have a PowerShell command that invokes a command on a remote machine to print out a debug message, and then prints out a debug message on the running machine, as follows:
function Start-DebugTest {
[cmdletbinding()]
param ()
$cmd = {
$DebugPreference = 'Continue'
Write-Debug -Message 'This is invoked DEBUG message'
}
$params = @{
ComputerName = $ip
Credential = $cred
ScriptBlock = $cmd
}
Invoke-Command @params
Write-Debug -Message 'This is a normal DEBUG message'
}
When I run the Start-DebugTest
command locally I see the following output:
DEBUG: This is invoked DEBUG message
DEBUG: This is a normal DEBUG message
When I run this through C# like this:
using (PowerShell powershell = PowerShell.Create())
{
var command = powershell.AddCommand("Start-DebugTest");
powershell.Runspace.SessionStateProxy.SetVariable("DebugPreference", "Continue");
PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
output.DataAdded += (sender, args) => DataAdded((PSDataCollection<PSObject>) sender, progress);
powershell.Streams.Debug.DataAdded += (sender, args) => StreamDataAdded((PSDataCollection<DebugRecord>) sender, args, "DEBUG", progress);
var resources = await Task.Factory.FromAsync(
powershell.BeginInvoke<PSObject, PSObject>(null, output),
asyncResult => powershell.EndInvoke(asyncResult));
return resources;
}
private void StreamDataAdded<T>(PSDataCollection<T> records, DataAddedEventArgs e, string msgType, IProgress<string> progress) where T : InformationalRecord
{
string msg = records[e.Index].Message;
progress.Report($"{msgType}: {msg}");
}
private void DataAdded(PSDataCollection<PSObject> myp, IProgress<string> progress)
{
Collection<PSObject> results = myp.ReadAll();
foreach (PSObject result in results)
{
progress.Report($"OUTPUT: {result.ToString()}");
}
}
I only receive the debug message running on the local machine and not the one from the invoked command, from either of the DataAdded
events:
DEBUG: This is a normal DEBUG message
If I see the output when running it locally, somehow the debug message is available. Is there any way to access it from C#?