formathighlightI came across a strange PowerShell feature while working on a StudioShell bug– you’ve gotta see this one for yourself…

Open a shell and run the following one-liner:

get-childitem ~ | foreach-object {
    if( $_ -match '^t' ) { 
        $_ | add-member -mem noteproperty -name writeerrorstream -value $true 
    } 
    $_
}

Take a look at the output.  Assuming you have a file or folder in your home directory that starts with the letter ‘t,’ you should see them in red (or whatever color you’ve configured your error output to be) co-mingling with all those non-t-starting file system thingies! 

WriteErrorStream seems to be a magic property PowerShell uses to format an object as if it were an error.  Works in the console host and the ISE.  Seriously, try it.

Note that I say it formats the object as if it were an error – that is, while it affects the coloring of that individual output record, it is unaffected by your  $ErrorActionPreference setting and doesn’t manipulate the $error magic variable.  It just colors those items. 

While I’m sure this isn’t behavior that one should rely upon, it does seems like a quick & dirty way to mark outputs in the shell.  Here’s a function I just added to my profile:

function format-highlight
{
    [cmdletbinding()]
    param( 
        [parameter(Mandatory=$true, position=0)]
        [scriptblock] 
        $filter,
        
        [parameter(ValueFromPipeline=$true)]
        $input 
    )
    
    process
    {
        $input | foreach { 
            if( &$filter ) { 
                $_ | add-member -mem noteproperty -name writeerrorstream -value $true 
            } 
            $_  
        }
    }
}

That makes using this feature a snap:

ls | format-highlight { $_.length -gt 1mb }