Jamal El Mouss
Jamal El Mouss

Reputation: 11

Powershell foreach and export-csv doesn't work

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

enter code here Code1
                                            # 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


                    code2
                    # 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
                        }`enter code here`

                        $cmde | Export-csv ($desti + "\XplanifTasks.csv") -Delimiter "," -NoTypeInformation`enter

Upvotes: 1

Views: 318

Answers (2)

TheMadTechnician
TheMadTechnician

Reputation: 36287

I would be very tempted to use the Task Scheduler com object to do this so that I didn't have to create remote sessions on all of the computers, just connect to their task scheduler service. This does require that you enable remote management of scheduled tasks in the firewall, but if you're allowing remote powershell you probably allow this as well.

$Scheduler = New-Object -ComObject Schedule.Service
Get-Content $fileComputerNames -PipelineVariable 'Server' |ForEach-Object{
    $i=0
    # Try to connect to remote task scheduler up to 3 times
    While(!$Scheduler.Connect($Server) -eq 0 -or $i -eq 3){$i++}
    # If we aren't connected to the right server throw a warning and move on to the next server
    If(!$Scheduler.TargetServer -eq $Server){Write-Warning "Unable to connect to $Server"; Continue}
    $RootFolder = $Scheduler.GetFolder('\')
    $RootFolder.GetTasks(1) | # The '1' indicates we want to include hidden tasks
        Where {$_.Principal.userid -eq "ZRES\XPLANIF"} |
        Select @{LABEL='Serveur';EXPRESSION={$server}}, Name, LastRunTime, NextRunTime
} | Export-Csv "$desti\XplanifTasks.csv" -Del ',' -NoType

Upvotes: 1

Scripticated
Scripticated

Reputation: 47

There are a few things funny with the code as it stands.

  1. It appears as though your building an array $cmde of script blocks. Adding one script block for every Server in $fileComputerNames, even though those script blocks are not Server specific. (Does Invoke-Command even accept an array of script blocks? I would expect it to error out)
  2. Your then piping this $cmde to Export-CSV
  3. While there is nothing wrong with building an array using += its very inefficient in PowerShell and should be avoided if the array will be Large as it will significantly slow down your script.

I cannot fully vet what your trying to do but assuming your Invoke Command Does what you want on one computer something like the following should work for you.

...
$cmde = {Get-ScheduledTask | Where {$_.Principal.userid -eq "ZRES\XPLANIF"} | Get-ScheduledTaskInfo}
$SchTasks = Foreach ($server in Get-Content $fileComputerNames) {
    Invoke-Command -ComputerName $server -ScriptBlock $cmde |
    Select @{LABEL='Serveur';EXPRESSION={$server}}, TaskName,LastRunTime,NextRunTime
}

$SchTasks | Export-csv ($desti + "\XplanifTasks.csv") -Delimiter "," -NoTypeInformation

Upvotes: 1

Related Questions