For loop and counter




I tried to write this script:

For ($Counter = 0; $Counter -le 15; $Counter++)
    Write-Host $Counter -ForegroundColor $Counter

How come the Write-Host command also accepts a numeric object like $Counter ?





2 Replies



I don't understand the question.


PowerShell can write anything that contains a definition for the ToString() method, which is probably pretty close to every class that comes out of Microsoft (and most other reputable vendors.)


It's far more surprising if and when ToString() hasn't been defined.


Looking at your command, there's two distinct things going on:


  1. The first $Counter causes PowerShell to look for a ToString() method, which given this is an integer type, would be this one:
  2. The second time $Counter is mentioned is after -ForegroundColor, which is an enumeration:


For point 2, an enumeration can be referred to in two ways:


  1. By using its label (in this case the name of a colour); or
  2. By its ordinal reference - or number (in plain English.)


So, when you pass in $Counter, which is an integer, PowerShell (actually, .NET) accepts that - so long as it's a value that matches a value defined in the enumeration. In this specific case, the enumeration is named System.ConsoleColor.


Here's the reference for System.ConsoleColor:



And here's an example of how you can inspect an enumeration in code:



In both cases, you can plainly see the relationship between an enumeration's label and its ordinal (numeric) value.






The Write-Host cmdlet's primary purpose is to produce for-(host)-display-only output, such as printing colored text like when prompting the user for input in conjunction with Read-Host. Write-Host uses the ToString() method to write the output. By contrast, to output data to the pipeline, use Write-Output or implicit output.