Home > OS >  Delete Folders from CSV List
Delete Folders from CSV List

Time:03-07

I have a CSV file that lists 59 folder paths that I wish to delete. This is the code I am using-

$Folders = Import-Csv -Path "path to csv file"

foreach ($folder in $Folders){
if (Test-Path $folder) {
 
    Write-Host "Folder Exists"
    Remove-Item $folder -Recurse -Force
}
else
{
    Write-Host "Folder Doesn't Exists"
}

}

The CSV file looks like this:

folders
E:\path1
E:\path2
E:\path3

However the script does not work and it returns "Folder Doesnt Exist", though they do exist. What am I missing?

CodePudding user response:

$Folders contains rows from the original file. So each $folder is a row from the original file, not the column value, i.e. file name.

You access columns from the rows by using the header name, "folders" in your case:

$Folders = Import-Csv -Path "path to csv file"

foreach ($folder in $Folders) {
   if (Test-Path $folder.folders) {
 
       Write-Host "Folder Exists"
       Remove-Item $folder.folders -Recurse -Force
   }
   else
   {
       Write-Host "Folder Doesn't Exists"
   }
}

In short: Use $folder.folders to access the actual value.

You can see the difference like so:

 PS> Import-CSV .\foo.csv | % { Write-host $_ }
 @{folders=E:\path1}
 @{folders=E:\path2}
 @{folders=E:\path3}

 PS> Import-CSV .\foo.csv | % { Write-host $_.folders }
 E:\path1
 E:\path2
 E:\path3



 

CodePudding user response:

Complementing Christian.K's helpful answer, you may use the following alternative ways:

Use Select-Object with parameter -ExpandProperty (alias -Expand) to extract the Folders column directly at the source:

$Folders = Import-Csv -Path "path to csv file" | Select-Object -Expand Folders

Use member enumeration to create an array of strings from the Folders property :

foreach ($folder in $Folders.Folders) { 
    ...
}
  • Related