简体   繁体   English

Powershell删除基于CSV的文件

[英]Powershell to Delete files based on CSV

I am trying to delete bunch of files based on a csv file. 我试图删除基于csv文件的文件堆。 Files listed in the csv file should be deleted from the target file share. csv文件中列出的文件应从目标文件共享中删除。 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
}

According to your comment, you have some empty filenames in the csv file. 根据您的评论,csv文件中有一些空文件名。 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"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM