0

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
  • 2
    Remove Update-Csv. Commented Jun 7, 2019 at 14:24

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

So it won't mess up the to loop changing the active table it is running after? - doing the ´$row.Status = "Done"´
I had overlooked the missing -Delimiter ';'. Should work now as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.