$FormatEnumerationLimit Scoping Issues

by Nov 21, 2018

As shown in the previous tip, the secret $FormatEnumerationLimit variable determines how many array elements are shown in output before the output is truncated. Here is an example illustrating the difference again:

$default = $FormatEnumerationLimit

Get-Process | Select-Object -Property Name, Threads -First 5 | Out-Default
$FormatEnumerationLimit = 1
Get-Process | Select-Object -Property Name, Threads -First 5 | Out-Default
$FormatEnumerationLimit = -1
Get-Process | Select-Object -Property Name, Threads -First 5 | Out-Default

$FormatEnumerationLimit = $default

The output looks similar to this:

 
Name       Threads                    
----       -------                    
acrotray   {3160}                     
AERTSr64   {1952, 1968, 1972, 8188}   
AGSService {1980, 1988, 1992, 2000...}
armsvc     {1920, 1940, 1944, 7896}   
ccSvcHst   {2584, 2644, 2656, 2400...}



Name       Threads  
----       -------  
acrotray   {3160}   
AERTSr64   {1952...}
AGSService {1980...}
armsvc     {1920...}
ccSvcHst   {2584...}



Name       Threads
----       -------
acrotray   {3160}
AERTSr64   {1952, 1968, 1972, 8188}
AGSService {1980, 1988, 1992, 2000, 2024, 7932}
armsvc     {1920, 1940, 1944, 7896}
ccSvcHst   {2584, 2644, 2656, 2400, 3080, 3120, 3124, 3128, 3132, 3136, 3140,...
 

However, this seems to fail when used in functions (or script blocks altogether, for that matter):

function Test-Formatting
{
  $FormatEnumerationLimit = 1
  Get-Process | Select-Object -Property Name, Threads -First 5 
}

Test-Formatting

Despite setting $FormatEnumerationLimit to 1, arrays continue to display the default 4 elements. This is because $FormatEnumerationLimit is honored only on a global scale. You must change the variable in global scope to take effect. A function would therefore need to use an approach like this:

function Test-Formatting
{
  # remember the current setting
  $default = $global:FormatEnumerationLimit
  
  # change on global scope
  $global:FormatEnumerationLimit = 1
  Get-Process | Select-Object -Property Name, Threads -First 5 

  # at the end, clean up and revert to old value
  $global:FormatEnumerationLimit = $default
}

Test-Formatting

Twitter This Tip! ReTweet this Tip!