PowerShell命令问题:重命名后无法删旧文件及长路径解决方案
PowerShell远程清理旧文件问题与解决方案
问题描述
我从网上整理了这条PowerShell命令:
Get-ChildItem -Path “\$pc\c$\users\” -recurse -force | where {$_.LastWriteTime -le $(get-date).Adddays(-180)} | Rename-Item -NewName { $_.name.substring(0, [Math]::Min($_.BaseName.length, 3))} | rm -confirm:$false -ErrorAction ignore
我的需求是把所有超过180天的旧文件重命名为前3个字符后删除,但这个命令有两个问题:
- 重命名后无法删除文件
- 执行一次后就没法再运行,因为重命名后的文件修改时间被更新,不再满足“超过180天”的判定条件
想请教能不能修改原命令,或者单独写一条命令来删除仅3字符长度的文件?
解决方案
感谢@lit提供的思路,最终解决方法是修改路径格式以支持长路径读取:
存在问题的命令(会遗留文件)
Get-ChildItem -Path “\remotepc\c$\users\” -recurse -force | where {$_.LastWriteTime -le $(get-date).Adddays(-180)} | Remove-Item -recurse
正确命令
Get-ChildItem -Path “\?\UNC\remotepc\c$\users\” -recurse -force | where {$_.LastWriteTime -le $(get-date).Adddays(-180)} | Remove-Item -recurse
该命令可删除远程计算机上6个月未访问的用户文件和文件夹,同时支持处理路径长度超过260字符的文件。
内容的提问来源于stack exchange,提问作者jorge google
相关产品推荐
相关产品推荐

