Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ninmonkey/11ceda9e1775e1bb0667d498cec485b5 to your computer and use it in GitHub Desktop.
Save ninmonkey/11ceda9e1775e1bb0667d498cec485b5 to your computer and use it in GitHub Desktop.
Quick example of saving results to arrays when implicit output was getting complicated
using namespace System.Collections.Generic
# Say you want one table that has all results, with fixed columns
[list[Object]]$Summary = @()
# and a second array that's just errors with extra info
[list[Object]]$ErrorSummary = @()
foreach( $user in $UserCsv ) {
$result = [pscustomobject]@{
FirstLast = $Name
EmployeeNumber = $Number
Result = 'Ok'
}
try {
# maybe throws ...
$Summary.Add( $Result )
}
catch {
# write the error to the error stream and save
Write-Error "User Iter failed: $_"
$result.Result = $_.Exception.Message
$Summary.Add( $Result )
$ErrorSummary.Add(
[pscustomobject]@{
ExceptionObject = $_
FirstLast = $Name
EmployeeNumber = $Number
When = (Get-Date).ToString('o')
}
)
}
}
$exportExcelSplat = @{
Title = 'All Results'
TableName = 'SummaryData'
WorksheetName = 'Summary'
TableStyle = 'Light2'
Path = 'c:\foo\out.xlsx'
}
$Summary | Export-Excel @exportExcelSplat
$exportExcelSplat = @{
Title = 'Error Context'
TableName = 'Errors'
WorksheetName = 'ErrorInfo'
TableStyle = 'Light2'
Path = 'c:\foo\out.xlsx'
}
$ErrorSummary | Export-Excel @exportExcelSplat
# If you really want to ensure you have fixed columns for your summary
# then check out classes. You can use them sort of like a "record struct"
# Compared to [PSCO] which allow arbitrary and unbalanced names
[List[SummaryRecord]] $SummaryRecords = @()
class SummaryRecord {
[string] $FirstLast
[int] $EmployeeNumber
[string] $Result
}
# Classes let you use the hashtable contructor syntax
$SummaryRecords.Add(
[SummaryRecord]@{
FirstLast = 'bob'
EmployeeNumber = 123
Result = 'Success'
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment