Possible to have different array names when write-output PSCustomObject]@{ in my function?

Viewed 28

Is there any way to name the variable for an array something in my Catch { and then have another array name for the array inside Try/script part of my function?

Cause when i try doing like this $computerObject = [PSCustomObject]@{ and then doing Write-Output $computerArray i can only get either my variables inside Try/script array being displayed inside Powershell window. Or only get the $error message from my Catch.. Is there any way to name each array something so i can do like below.

write-host "Results" Write-Output $computerArray - display my first array here

write-host "Failed: computerlist" -foregroundcolor red Write-Output $computerArray2 - display $error computers here. $error should just include computers who did not answer to ping and other stuff from my invoke-command computerlist.txt

The only true answer to why i need this separately is that sometimes i want my array in a CSV file. And sometimes i just want to copy info directly from Powershell window. And then its more practical to have failed computers separated and not in the same array output.

1 Answers

This function (as mentioned in comments) doesn't leverage the CIM cmdlets parallel capabilities, would recommend some tweaks to it but to answer the actual question, how can you "split" the output between success and fail:

The function as-is, doesn't require any modification to achieve this, it's try and catch blocks are outputting objects with the same properties and luckily one of those properties is Error and it's value is a boolean so you can simply first query all the computers and then split the result using .Where with Split mode.

The code would be like this:

$computers = 'computer1', 'computer2', ....

$computerArray = foreach($computer in $computers) {
    Get-ComputerInformation -ComputerName $computer
}

# now we can split between FAIL and SUCCESS
$fail, $success = $computerArray.Where({ $_.Error }, 'Split')
$success | Export-Csv path\to\success.csv -NoTypeInformation
$fail | Export-Csv path\to\fail.csv -NoTypeInformation
Related