there are better ways to do it.
currently you’re taking the whole object copying it then adding the last item, then deleting the old object, then repeating for each item in the loop
just spit your object out to the pipeline and deal with it there (weather that’s to a variable on the for each or a variable elsewhere or passed to another function)
also precreating these `$output = @()` and `[PSCustomObject]$h = @{}` is not needed
your example could be
$file = Get-Content $pathtofile
$output = foreach ($item in $file){
[PSCustomObject]@{
Name = $item.name
Prop1 = $item.thing1
Prop2 = $item.thing3
}
}
$output will be an array if the loop produces multiple items, and a single item if the loop outputs only one.
Internally, PowerShell is capturing the loop output in an ArrayList and converting it to an array when it completes.
You could also write:
[array]$output = foreach …
or
$output = @(
foreach ($item in $file){
[PSCustomObject]@{
Name = $item.name
Prop1 = $item.thing1
Prop2 = $item.thing3
}
}
# more logic can go here
)