2

I am trying to delete bunch of files based on a csv file. Files listed in the csv file should be deleted from the target file share. When I run the script I am in the target folder but I am getting the following error:

Remove-Item : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties 
do not match any of the parameters that take pipeline input.
At line:9 char:56
+     Get-Childitem | where {$_.Name -match $filename} | Remove-Item -verbose -$fi ...
+                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (gp.html:PSObject) [Remove-Item], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.RemoveItemCommand

Code below:

$csvFile = Import-csv "C:\\DeleteFiles.csv"
foreach($user in $csvFile)
{
    $filename = $user.FileName
    write-host $filename    
    Get-Childitem | where {$_.Name -match $filename} | Remove-Item -verbose -$fileName
}

1 Answer 1

2

According to your comment, you have some empty filenames in the csv file. This solution should be more robust:

$csvFile = Import-csv "C:\\DeleteFiles.csv"
foreach($user in $csvFile)
{
  $filename = $user.FileName
  write-host "The filename is '$filename'" 
  if (test-path $filename) 
  {
    Remove-Item -verbose $fileName
  }
  else
  {
    Write-Host "File '$filename' not found"
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your code deleted all of my files. Luckily I was doing a test again c:\temp folder not the actual folder. So I changed the code to Remove-Item -verbose $filename but getting following error. Remove-Item : Cannot bind argument to parameter 'Path' because it is an empty string.
I am sorry Swoogan, I did not mean to critic is negatively. Your solution worked like charm. and you are correct there are some empty row in the csv files. I need to make sure there are not empty rows. Thanks again
No offence taken. I'm just glad you were working in isolation. But this is a good lesson; PowerShell cmdlets often take an empty string to mean everything. I've been burned by this before, as well.

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.