[英]Remove-Item is not removing any files
我正在尝试从网络上的 80 多台服务器中删除一些文件。 代码运行良好,甚至说文件正在被删除,但是当我去检查服务器时......文件仍然存在。 我不太确定从这里去哪里。
这是我的代码如下:
$filelist = @("/Contracts/Contract.con",
"/Contracts/DefaultFinanceSale.con",
"/Contracts/DefaultRentalReturnOrder.con",
"/Contracts/EPOSSchedule.con",
"/Contracts/SMSAuthorization.con",
"/Tags/BarCode.tag",
"/Tags/Sample 4x6.TAG",
"/Tags/Sample FullPage.TAG",
"/Tags/Sample FullPageBundle.TAG",
"/Tags/Sample FullPageBundle2.TAG",
"/Tags/Sample FullPagePackage.TAG",
"/Tags/Sample FullPagePackage2.TAG",
"/Tags/Sample(2).tag")
$computerlist = Get-Content C:\support\scripts\server_list.txt
$Log = "c:\support\scripts\logs\Test_Delete_Old_Files_$(Get-Date -Format 'yyyyMMddhhmmss').log"
Start-Transcript -path $Log -append -Force -NoClobber
foreach ($file in $filelist){
foreach ($computer in $computerlist){
Write-Host -ForegroundColor Yellow "Analysing $computer"
$newfilepath = Join-Path "\\$computer\" "$file"
if (test-path $newfilepath){
Write-Host "$newfilepath file exists"
try
{
Get-ChildItem $newFilePath -Force -Recurse | %{$_.Attributes = "readonly"} -ErrorAction Stop | Remove-Item
}
catch
{
Write-host "Error while deleting $newfilepath on $computer.`n$($Error[0].Exception.Message)"
}
Write-Host "$newfilepath file deleted"
} else {
Write-Information -MessageData "Path $newfilepath does not exist"
}
}
停止成绩单
您是否尝试将 -Force 添加到 remove-item 的末尾?
您应该反转两个 foreach 循环,并首先通过$computerlist
,否则您会为列表中的每个文件在计算机之间切换。
然后,正如所评论的,您的$filelist
变量包含Files 的部分路径,而不是目录。 由于文件没有像目录或磁盘那样的任何子项,因此Get-ChildItem
将找不到任何内容。
要同时删除设置为只读(和/或隐藏)的项目,您可以在 Remove-Item 上使用-Force
开关。
尝试使用这样的嵌套循环:
foreach ($computer in $computerlist) {
Write-Host -ForegroundColor Yellow "Analysing $computer"
foreach ($file in $filelist) {
$newfilepath = Join-Path -Path "\\$computer" -ChildPath $file
if (Test-Path -LiteralPath $newfilepath -PathType Leaf) {
try {
Remove-Item -LiteralPath $newfilepath -Force -ErrorAction Stop
Write-Information "$newfilepath file deleted on computer '$computer'"
}
catch {
Write-Warning "Error while deleting $newfilepath on computer '$computer'.`r`n$($_.Exception.Message)"
}
}
else {
Write-Information -MessageData "File $newfilepath does not exist on computer '$computer'"
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.