Text moves more to the right when looping

This is my output below when creating a function with a for loop inside it:

NO      Type
--      ----

 1       System.Int32 
 2       System.Int32 
 3       System.Int32 
 4       System.Int32 
 5       System.Int32 
 6       System.Int32 
 7       System.Int32 
 8       System.Int32 
 9       System.Int32 
 10          System.Int32   

You see that when 10 comes, it moves the System.Int32 more to the right. How do I change that inside my code? This is probably not related to only Powershell.

Code:

function CountTen() {
    [array]$ListOfNumbers = @()
    [array]$NumbersType = @()

    for ($i=1; $i -le 10; $i++) {
        $ListOfNumbers += ("`n", $i, "`t`t", ($i.GetType()))
    }

    Write-Host "NO`t`tType"
    Write-Host "--`t`t----"
    Write-Host $ListOfNumbers, "`t`t", $NumbersType
}

CountTen    

Answer

You should check formatting (-f) of PS. A sample can be found here: http://www.computerperformance.co.uk/powershell/powershell_-f_format.htm

So, for advanced formatting, the following pattern can be used:
format -f values
like

"text {x,xlength} text {y,ylength} text" -f xvalue, yvalue

where x (and y) are the position of the value listed behind -f. That value must appear in the text where {…} is placed. xlength (and ylength) is the width with which the appropriate value will be displayed. Lengths are optional.

The current problem can be redefined this way using specific formatting:

function CountTen() {
    $format = "{0,5} {1}"
    [array]$ListOfNumbers = @()
    [array]$NumbersType = @()

    $format -f "NO", "Type"
    $format -f "--", "----"

    for ($i=1; $i -le 10; $i++) {
        $format -f $i, $i.GetType()       
    }
}

CountTen

Here the integers and their header is aligned “flush right” (as figures often are) in a 5 character long field.

Attribution
Source : Link , Question Author : Zrg , Answer Author : Gombai Sándor

Leave a Comment