I have a question about the order of output from a Powershell script. The order changes if I run the code from a script compared to just running it line for line in the console. I'd like to understand what causes this.
For example:
$Items = @()
1..5 | % {
$Item = [PsCustomObject]@{ Name = "Item$_" }
$Items += $Item
Write-Host "Item$_ has been added"
}
$Items
ForEach ($Item in $Items) {
Write-Host "Displaying $($Item.Name)"
}
When I run the above code directly from the console I get the order I expect:
Item1 has been added
Item2 has been added
Item3 has been added
Item4 has been added
Item5 has been added
Name
----
Item1
Item2
Item3
Item4
Item5
Displaying Item1
Displaying Item2
Displaying Item3
Displaying Item4
Displaying Item5
However, when I run it as a script the order changes:
Item1 has been added
Item2 has been added
Item3 has been added
Item4 has been added
Item5 has been added
Displaying Item1
Displaying Item2
Displaying Item3
Displaying Item4
Displaying Item5
Name
----
Item1
Item2
Item3
Item4
Item5
The output of the call to $Items comes after all Write-Host statements, even though it comes before them. However, if I change the call from $Items to $Items.Name, the order is correct.
Item1 has been added
Item2 has been added
Item3 has been added
Item4 has been added
Item5 has been added
Item1
Item2
Item3
Item4
Item5
Displaying Item1
Displaying Item2
Displaying Item3
Displaying Item4
Displaying Item5
Why is that? How could I output those items (not just one property) display in the order I want?