Set-PSDebug -Trace and runspaces

by yesffan at 2013-02-27 13:24:39

Hi. I have a script that executes other scripts using runspaces. In some cases, we wanted to be able to trace those other scripts (for debugging purposes) but for some reason, Set-PSDebug doesn’t seem to work at all under a runspace. Take for example the following code:

$config = [Management.Automation.Runspaces.RunspaceConfiguration]::Create()
$runSpace = [RunSpaceFactory]::CreateRunspace($host, $config)
$runSpace.ApartmentState = "STA"
$runSpace.ThreadOptions = "ReuseThread"
$myoption = ($runSpace.Debugger -eq $null)
$runSpace.Open()
$runSpace.SessionStateProxy.setVariable("DebugPreference", "Continue")

$testcode = @"
Write-Debug ‘Setting debug trace’
Set-PsDebug -Trace 1
Write-Host ‘Console message’
if ($host.Version.Major -ne 2) {
Write-Host ‘This code has not been tested in Powershell higher than version 2’
}
Write-Debug ‘Debug message’
"@

$posh = [PowerShell]::Create()
$posh.Runspace = $runSpace
$ar = $posh.AddScript([scriptblock]::Create($TestCode)).BeginInvoke()
$r = $posh.EndInvoke($ar)


After executing this code, I can see the Write-Debug messages, the Write-Host message but no trace message. Is there a Powershell variable (like DebugPreference) or flag to enable tracing within a runspace? I’ve been googling this issue with no results. Just in case, I’m using Powershell v2.

Thanks in advance for any help,

Fernando
by poshoholic at 2013-02-27 13:48:30
Hi Fernando,

I tested this using PowerShell 2 in both STA and MTA mode and PowerShell 3. On PowerShell 2, you’re right, the tracing doesn’t come back as you expect. On PowerShell 3 you get back the trace messages. Seems like maybe they fixed a bug in PowerShell 3.0 since it works there. Since it’s working in v3 though and not in v2, I don’t know what else can be done to make this work as you expect in v2.
by yesffan at 2013-02-28 07:31:53
Thanks Kirk for your help. I guess we will have to debug the hard way until we can upgrade to v3. Thanks again!