![](/img/trans.png)
[英]PowerShell script to delete files from list and output list of deleted file
[英]Delete a list of files from a list of servers in powershell
我需要從服務器列表(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
$ 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來刪除整個子樹(所有文件,子目錄和子目錄中的文件)。 如果(如您的示例所示)$ REMOVE僅包含文件而不包含目錄,則不需要-Recurse。
另外,如果任何文件名包含空格或特殊字符,最好對路徑雙引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.