0

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?

1
  • 1
    You should debug your script. As a minimum, add to your logs $folder name, e.g. Write-Host "Folder $folder Doesn't Exists" Commented Mar 6, 2022 at 9:25

2 Answers 2

3

$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



 
Sign up to request clarification or add additional context in comments.

Comments

1

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) { 
    ...
}

Comments

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.