Mighty Drunken
Mighty Drunken

Reputation: 19

Import-CSV messing up filenames

I simply want to take a list of filenames from a text file and delete them. I have some very simple code but somehow it is going wrong.

$files = Import-Csv C:\temp\PS\duplicate3.csv
   foreach ($file in $files) {  
        Remove-Item -LiteralPath $file -WhatIf      
    }
write-host -foregroundcolor blue  "Delete complete"

In the csv file are just a list of paths like

C:\temp\test.txt
D:\Photos\Camera\IMG_20190523_151236(1).jpg

I get the error, for each line

Remove-Item : Cannot find drive. A drive with the name '@{C' does not exist.'

What is happening and how can I fix this?

Upvotes: 0

Views: 49

Answers (1)

Bacon Bits
Bacon Bits

Reputation: 32170

If you use Import-Csv, the command will assume that the first row is a header row. If there isn't a header in the first row, you need to specify it. Then, if you want to refer to a column later on, you need to specify the correct header. Import-Csv is designed to work with a table, so each row is assumed to have multiple properties.

$files = Import-Csv C:\temp\PS\duplicate3.csv -Header Path
   foreach ($file in $files) {  
        Remove-Item -LiteralPath $file.Path -WhatIf      
    }
write-host -foregroundcolor blue  "Delete complete"

If I'm understanding your file format right, you should probably just use Get-Content instead of Import-Csv.

$files = Get-Content C:\temp\PS\duplicate3.csv
   foreach ($file in $files) {  
        Remove-Item -LiteralPath $file -WhatIf      
    }
write-host -foregroundcolor blue  "Delete complete"

Upvotes: 2

Related Questions