This snippet show how to Collect objects in an array and list them.
Collect objects in an array is very usefull to pass information between functions in a flow. For instance you can use this technique in a loop to collect results and after show a summary listing collected objects.
# Objects ::: Collect in an array and list them # www.PowerShellExamples.com # Declare array of objects to collect them -_- $resultObjArr = @() #Create sample Object -_- $resultObj=[PSCustomObject]@{ ExitCode = 2 ExitMessage = "Sample Object" } # Add to Array $resultObjArr += $resultObj # Show Result Summary report $resultObjArr | Format-Table -Wrap | Out-String | Write-Host -ForegroundColor Green
Copy text below into a power shell session and execute to see the code in action.
# Practical Sample # Sample: Objects ::: Collect in an array and list them # www.PowerShellExamples.com # Declare array of objects to collect them -_- $resultObjArr = @() # Create multiple result objects for ($i = 0; $i -lt 5; $i++) { #Create sample Object -_- $resultObj=[PSCustomObject]@{ Target = "Element $i" ExitCode = 2 ExitMessage = "Sample Object" } # Update Result Object Properties if($i -eq 1 -or $i -eq 3){ $resultobj.ExitCode = "Ok" $resultObj.ExitMessage = "Odd Number." }else{ if($i -eq 0){ $resultobj.ExitCode = "Error" $resultObj.ExitMessage = "Sample Error." }else{ $resultobj.ExitCode = "Warn" $resultObj.ExitMessage = "Sample Warning." } } # Add to Array $resultObjArr += $resultObj } # Show Result Summary report $resultObjArr | Format-Table -Wrap | Out-String | Write-Host -ForegroundColor Green
PS C:\> Target ExitCode ExitMessage ------ -------- ----------- Element 0 Error Sample Error. Element 1 Ok Odd Number. Element 2 Warn Sample Warning. Element 3 Ok Odd Number. Element 4 Warn Sample Warning.