1

when i tried to extact results from this code

$Output = @()
foreach($emailproxy in $emailproxies)
{
if($emailproxy.Mail -like "*com" -or $emailproxy.Mail -like "*org"){ Write-Host $emailproxy.Mail} 
 $Output = New-Object -TypeName PSObject -Property @{
        Mail = $emailproxy.Mail
    } | Select-Object Mail
}

$Output | Export-Csv C:\TempDownloads\results.csv

I only get 1 result .. why is that ?

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
Wiktor
  • 581
  • 1
  • 12
  • 23

2 Answers2

2

For each iteration in the loop, you are assigning (overwriting) the value directly to the $Output variable, instead of adding the value to the array.

Inside the for loop, you need to replace $Output = with $Output +=.

  • $Output = <new value> -> Assign <new value> to $Output variable, existing value of $Output is overwritten and lost.

  • $Output += <new value> is equivalent to $Output = $Output + <new value>, where <new value> and current value of $Output are first combined and then assigned to $Output.

  • 2
    Good explanation; @WiktorKostrzewski, while this is the immediate solution to your problem, incrementally "extending" an array in a loop is inefficient, because a _new_ array must be created behind the scenes in every iteration, given that arrays are _immutable_; a much more efficient approach is to use the `foreach` loop as an _expression_ and let PowerShell automatically collect the outputs in an array: `[array] $Output = foreach (...) { ... }` - see [this answer](https://stackoverflow.com/a/60029146/45375). – mklement0 Mar 15 '20 at 18:39
  • To compliment [mklement0](https://stackoverflow.com/users/45375/mklement0) comment, please have a look at: [Why should I avoid using the increase assignment operator (+=) to create a collection](https://stackoverflow.com/q/60708578/1701026) – iRon Mar 16 '20 at 15:17
0

This is because you are overwrighting the variable $output each time. You need to append properties to the psobject using add-member

Output = New-Object -TypeName Psobject 
foreach($emailproxy in $emailproxies) { if($emailproxy.Mail -like "*com" -or $emailproxy.Mail -like "*org"){ Write-Host $emailproxy.Mail} 
$Output | Add-Member -MemberType NoteProperty -Name "Mail" -Value $_.mail
}
 $Output | Export-Csv "filepath"
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • Add-Member : Cannot bind argument to parameter 'InputObject' because it is null. At line:3 char:11 + $Output | Add-Member -MemberType NoteProperty -Name "Mail" -Value $_. ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Add-Member], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddMemberCommand Add-Member : Cannot bind argument to parameter 'InputObject' because it is null. – Wiktor Mar 15 '20 at 16:34
  • The intent is to create an _array_ of custom objects, to be collected in `$Output`. – mklement0 Mar 15 '20 at 18:43