2013-06-24 60 views
0

我需要从服务器列表(computer-list.txt)中删除一列文件(在remove-files.txt中)。我尝试了以下方法,但没有奏效,我希望有人能帮助我纠正我的错误。从PowerShell中的服务器列表中删除文件列表

$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} 

ERROR


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 
+0

尝试包装你的变量:删除项目“\\ $计算机\ $ DESTINATION \ $删除”-Recurse} –

+0

是的,我同意,如果任何文件名包含空格或shell特殊字符。但是,这不是这个错误的原因。错误的原因是$ REMOVE是一个多值数组,扩展为文件名列表而不是单个文件名。 –

回答

1

$ 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与目录删除整个子树(子目录中的所有文件,子目录和文件)。如果(如您的示例所示)$ REMOVE仅包含文件而不包含目录,您不需要-Recurse。

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

+0

谢谢你的帮助!正如你所解释的,我试图删除一些文件以及一些目录 – olufs3n