New Delayed Output in PowerShell 5.0

by Jul 20, 2016

PowerShell 2+

Let’s do two things. First, have a look at a useful small new function that does DNS resolution. Then, let’s discuss why this function can behave differently in PowerShell 5.0.

Here is the function:

function Get-HostByName
{
  param
  (
    [Parameter(Mandatory=$true,ValueFromPipeline)]
    $hostName
  )
  
  begin
  {
    Write-Warning 'Starting!'
  }
  process
  {
    try
    {
      [Net.Dns]::GetHostByName($hostName)
      
    }
    catch
    {
      Write-Warning "Error occured: $_"
    }
  }
  end
  {
    Write-Warning 'Done!'
  }
}

When you submit host names to it, it asks DNS to resolve these names. The output should look similar to this:

 
PS>  Get-HostByName microsoft.com
WARNING:  Starting!
 
HostName                   Aliases                    AddressList              
--------                   -------                    -----------              
microsoft.com              {}                         {104.43.195.251,  23.10...
WARNING:  Done!
 
 
 
PS>  'microsoft.com','powershell.com','powershellmagazine.com','powertheshell.com' |  Get-HostByName
WARNING:  Starting!
 
HostName                   Aliases                    AddressList
--------                   -------                    -----------
microsoft.com              {}                         {104.43.195.251,  23.10...
powershell.com             {}                         {65.38.114.170}
powershellmagazine.com     {}                         {206.217.196.220}
powertheshell.com          {}                         {104.24.124.64,  104.24...
WARNING:  Done! 
 

In PowerShell 5.0, though, the output of “WARNING: Done!” may appear before the actual data is displayed.

This is because PowerShell 5.0 caches the output data for a couple hundred milliseconds to determine how much room the data needs. This enables PowerShell 5.0 to better calculate column widths in tabular output. The backdraw is that due to the caching, the output of data that is emitted by an end-block may be messed up.

Twitter This Tip! ReTweet this Tip!