Select files based on CSV with Powershell
Recently, my girlfriend told me that she has to go through 4000 lines of CSV and select images based on their ids in the file. It would be a time consuming and more importantly super boring activity. Surely I can help her out.
The CSV format is similar to the following.
id,image_id
123,1
124,2
125,2
126,
127,3
The important things are that
- image id might be empty and
- same image can be assigned to multiple lines.
She doesn’t have administrator rights over her machine but it runs Windows 7 so there is Powershell available, so let’s try to write a simple script.
The idea is that firstly we will go to the directory with images and create a folder where we place a copy of selected files.
After that, we gonna run through each line of the CSV (note that we expect it to be in the same folder) and copy an item that matches the image id in the file.
cd to/the/directory
mkdir export
Import-Csv .\export.csv | foreach { if ($_.plan -ne "") { $_.plan_id + ".jpg" } } | select -uniq | foreach { Copy-Item $_ "export/$_" }
A few minutes of programming and I saved Bara hours spent on this mundane task that is also error-prone.