Powershell foreach and export-csv doesn't work

Hello Community

I use powershell V3 and / or powershell V4 it’s been a few days since I’m on this issue but no solution so far.

I explain, I have a vulgar powershell with an input file (list of servers) on which I wish to apply a treatment via a loop foreach and, retrieve the output in a csv.

The loop seems to work however, on an input file of 100 lines only the last one is export (the previous occurrences are overwritten) why I do not know. I have already tried to readjust the script by adding variables for incrementation (see code if below) but without success.

Can you help my to salve this case please?

# Emplacement fichierSource
$fileComputerNames = "E:\ReportXplanif\ServeursIUCR2K12.txt"
# Write-Host $fileComputerNames
# Emplacement fichierDestination
$desti = "E:\ReportXplanif"
# Write-Host $desti
Foreach ($server in Get-Content $fileComputerNames) {
    $cmde = {Get-ScheduledTask | Where {$_.Principal.userid -eq "ZRES\XPLANIF"} | Get-ScheduledTaskInfo}
    Invoke-Command -ComputerName $server -ScriptBlock $cmde |
        Select @{LABEL = 'Serveur'; EXPRESSION = {$server}}, TaskName, LastRunTime, NextRunTime
}
Export-csv ($desti + "\XplanifTasks.csv") -Delimiter "," -NoTypeInformation
# Emplacement fichierSource
$fileComputerNames = "E:\ReportXplanif\ServeursIUCR2K12.txt"
# Write-Host $fileComputerNames
 
# Emplacement fichierDestination
$desti = "E:\ReportXplanif\"
# Write-Host $desti
 
$cmde = @()
Foreach ($server in Get-Content $fileComputerNames) {
 
   
    $cmde += {Get-ScheduledTask | Where {$_.Principal.userid -eq "ZRES\XPLANIF"} | Get-ScheduledTaskInfo}
    Invoke-Command -ComputerName $server -ScriptBlock $cmde |
        Select @{LABEL = 'Serveur'; EXPRESSION = {$server}}, TaskName, LastRunTime, NextRunTime
}
   
$cmde | Export-csv ($desti + "\XplanifTasks.csv") -Delimiter "," -NoTypeInformation
 

Here is a generic example.

Foreach($Server in $ServerList){
    [array]$Output += Invoke-Command -ComputerName $Server -ScriptBlock { Get-Process | Select-Object -First 4 }
}

#Another way, The output will get stacked in the variable.
$Output  = Foreach($Server in $ServerList){
              Invoke-Command -ComputerName $Server -ScriptBlock { Get-Process | Select-Object -First 4 }
           }

You don’t even need to use Foreach here. -computerName accepts array of computers, you can pass $FileComputerNames directly to -ComputerName parameter.