views:

51

answers:

2

Hi everyone,

I am using Powershell 2.0 to write data to the Powershell's debug stream via Write-Debug function. Now I want to read that stream from the same powershell script. I tried to redirect the debug stream with "2>&1" but this works only for the error stream.

Is there a way to read the Powershell debug stream from a powershell script ?

Regards

A: 

It can be done but it is complex. See Oisin's writeup on script logging. In general, this issue of being able to redirect streams other than stdout and stderr has been logged as a suggestion on the connect site. You might want to vote on it.

Keith Hill
+1  A: 

You can also experiment with your function that will be called instead of cmdlet Write-Debug. Here is very quick implementation:

$global:__DebugInfo = new-object PSObject -prop @{
    Enabled=$false
    Messages=new-object System.Collections.ArrayList 
}

function Write-Debug { 
    param([Parameter(Mandatory=$true)][string]$Message)
    $d = Get-Command Write-Debug -CommandType cmdlet; & $d $Message; 
    if ($global:__DebugInfo.Enabled) {
        $global:__DebugInfo.Messages.Add($Message) > $null
    }
}
function Enable-Debug  {
    $global:DebugPreference = 'continue'
    $global:__DebugInfo.Enabled = $true 
}
function Disable-Debug {
    $global:DebugPreference = 'silentlycontinue'
    $global:__DebugInfo.Enabled = $false 
}

# test
Enable-Debug
Write-Debug 'this is test debug message'
Write-Debug 'switch off'
Disable-Debug
Write-Debug 'this message should not be included'

Write-Host "Debug messages:" 
Write-Host ($__DebugInfo.Messages -join "`n")
stej
Thanks ! It works very fine for my problem.
symbion