从powershell中的服务器列表中删除文件列表

时间:2013-06-24 17:03:00

标签: list file powershell delete-file

我需要从服务器列表(computer-list.txt)中删除文件列表(在remove-files.txt中)。我尝试过以下但是没有用,我希望有人可以帮我纠正我的错误。

$SOURCE = "C:\powershell\copy\data"
$DESTINATION = "d$\copy"
$LOG = "C:\powershell\copy\logsremote_copy.log"
$REMOVE = Get-Content C:\powershell\copy\remove-list.txt

Remove-Item $LOG -ErrorAction SilentlyContinue
$computerlist = Get-Content C:\powershell\copy\computer-list.txt

foreach ($computer in $computerlist) {
Remove-Item \\$computer\$DESTINATION\$REMOVE -Recurse}

错误


Remove-Item : Cannot find path '\\NT-xxxx-xxxx\d$\copy\File1.msi, File2.msi, File3.exe,          File4, File5.msi,' because it does not exist.
At C:\powershell\copy\REMOVE_DATA_x.ps1:13 char:12
+ Remove-Item <<<<  \\$computer\$DESTINATION\$REMOVE -Recurse}
+ CategoryInfo          : ObjectNotFound: (\\NT-xxxx-xxxxx\...-file1.msi,:String)     [Remove-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

1 个答案:

答案 0 :(得分:1)

$ REMOVE是一个数组,其元素是remove-list.txt的每一行。在\\$computer\$DESTINATION\$REMOVE中,$ REMOVE扩展为数组元素的列表。您的代码中没有任何内容告诉PowerShell迭代$ REMOVE的元素。你需要一个内循环:

foreach ($computer in $computerlist) {
  foreach ($file in $REMOVE) {
    Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
  }
}
是的,-Recurse究竟要完成什么?您是否认为这会使Remove-Item迭代路径末尾的文件名数组?这不是它的作用。 -Recurse开关告诉Remove-Item不仅删除路径指定的项目,还删除其所有子项目。如果要在文件系统上调用Remove-Item,则使用-Recurse with directories,删除整个子树(子目录中的所有文件,子目录和文件)。如果(如您的示例所示)$ REMOVE仅包含文件而不包含目录,则不需要-Recurse。

此外,如果任何文件名包含空格或特殊字符,最好重复引用路径。