0
votes

I have a foreach loop in PowerShell. It runs through some users moving data based on a CSV file. I would like to update the CSV file for each line that has bee ran, so a CSV looking like this:

Username;OldData;NewData;Status
User1;c:\Old;c:\new;Waiting
User2;d:\Old;D:\New;Waiting

Will as the last line in the first foreach loop (assuming the data has been copied) change the CSV to:

Username;OldData;NewData;Status
User1;c:\Old;c:\new;Done
User2;d:\Old;D:\New;Waiting

And again after User2 has finished update it to:

Username;OldData;NewData;Status    
User1;c:\Old;c:\new;Done
User2;d:\Old;D:\New;Done

What I do now is import the CSV with

$Table = Import-Csv c:\csv.csv

and then run the foreach (pseudo code)

foreach ($Row in $Table) {
    Copy-Content $row.OldData $row.NewData
    Update-Csv $row.Status = "Done"
}
1
Remove Update-Csv. - Ansgar Wiechers

1 Answers

2
votes

After following @AnsgarWiechers hint, save changed $Table with

$Table | Export-Csv C:\csv.csv -NoTypeInformation

To avoid processing the same line multiple times on successive runs, exclude the ones with Status Done

## Q:\Test\2019\06\07\SO_56495983.ps1

$File = '.\csv.csv' # 'c:\csv.csv'  #
$Table = Import-Csv $File -Delimiter ';'

foreach ($Row in ($Table|Where Status -eq 'Waiting')) {
    #Copy-Content $row.OldData $row.NewData
    $row.Status = "Done"
}

$Table
$Table | Export-Csv $File  -Delimiter ';' -NoTypeInformation