Capturing Write-Noun Cmdlet Output

I’m sure there’s a cleaner way to capture the output from Write-Host, Write-Verbose, etc.  However, I’m just going to “go caveman” in the words of a coworker and just hack around with the Verb-Transcript cmdlets.

Without further ado:

function Get-MisbehavingCmdletOutput
    param (
        [System.Management.Automation.Scriptblock]$ScriptBlock = $null,
        [string]$Path = "$env:temp\$([System.IO.Path]::GetRandomFileName())"

    if (!$ScriptBlock)
        write-host "$($MyInvocation.MyCommand.Name) -ScriptBlock not specified, required.  Stopped.";

    New-Item -ItemType Directory -Path $Path -ErrorAction SilentlyContinue -OutVariable $null | Out-Null;
    Remove-Item -Path $Path

    Start-Transcript -Path $Path -ErrorAction Stop | Out-Null;
    & $ScriptBlock;
    Stop-Transcript -OutVariable $null | Out-Null;

    $data = Get-Content -Path $Path;

    $end = $data.count - 6;
    $data[6..($data.count - 5)];

Comments (0)

Skip to main content