I need to delete a list of files (in remove-files.txt) from a list of server (computer-list.txt). I've tried the following but it didn't work, i am hoping someone can please help me correct my errors.
$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
$REMOVE is an array whose elements are each line of remove-list.txt. In \\\\$computer\\$DESTINATION\\$REMOVE
, $REMOVE expands to a list of the array's elements. There's nothing in your code that tells PowerShell to iterate through the elements of $REMOVE. You need an inner loop:
foreach ($computer in $computerlist) {
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
}
}
BTW, what exactly is -Recurse
intended to accomplish? Were you thinking that this would make Remove-Item iterate through an array of filenames at the end of the path? That's not what it does. The -Recurse switch tells Remove-Item to remove not only the item specified by the path, but all its children as well. If you're invoking Remove-Item on a filesystem, you'd use -Recurse with directories, to delete the entire subtree (all files, subdirectories, and files in the subdirectories). If (as your example implies) $REMOVE contains only files and not directories, you don't need -Recurse.
Also, it's a good idea to double-quote the path, in case any of the filenames contain spaces or special characters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.