Reputation: 14765
I'm trying to generate an output string like Item1, Item2
, that is joined with a comma separator. We do this by initiating an empty array in the Select-Object -Property
.
Check this code:
$Test = @(
[PSCustomObject]@{
Name = 'Test'
}
[PSCustomObject]@{
Name = 'Test2'
}
) | Select-Object -Property @{N = 'Problem'; E = { @() } },
@{N = 'EmployeeType'; E = { $null } }, *
foreach ($R in $Test) {
$R.Problem += 'Item1'
$R.Problem += 'Item2'
}
$Test | Select-Object -Property @{Name = 'Problem'; Expression = { $_.Problem -join "; " } }, * -ExcludeProperty Problem | fl
Result:
Problem : Item1Item2
Name : Test
Problem : Item1Item2
Name : Test2
Why is the property Problem
concatenated as a String
and not as an Array
? How can it be converted to an Array
?
Upvotes: 1
Views: 1188
Reputation: 27626
Unfortunately that way to make an empty array didn't work.
PS C:\users\js> $test[0].problem.gettype()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $test[0].problem.gettype()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\users\js> $test[0].problem -eq $null
True
By the way, using "+=" kills puppies.
Upvotes: 0
Reputation: 61263
To instantiate an empty array in the expression of the calculated property, @()
is not enough, because PowerShell will flatten that and it will become $null.
Use ,@()
instead
$Test = @(
[PSCustomObject]@{
Name = 'Test'
}
[PSCustomObject]@{
Name = 'Test2'
}
) | Select-Object -Property @{N = 'Problem'; E = { ,@() } },
@{N = 'EmployeeType'; E = { $null } }, *
foreach ($R in $Test) {
$R.Problem += 'Item1'
$R.Problem += 'Item2'
}
$Test | Select-Object -Property @{Name = 'Problem'; Expression = { $_.Problem -join "; " } }, * -ExcludeProperty Problem | fl
Returns:
Problem : Item1; Item2 EmployeeType : Name : Test Problem : Item1; Item2 EmployeeType : Name : Test2
Upvotes: 6