Powershell无法使用remove-item删除某些文件

时间:2013-01-11 11:16:29

标签: powershell powershell-v3.0

我创建了一个PS脚本,用于搜索文件服务器上的用户文件夹中的项目(电影,电视节目,exe文件等)。

我一遍又一遍地测试了这个脚本,除了一些.avi文件外,它还找到并删除了我想要的所有文件。我尝试过的一些文件名模式是:

  • *.s0*e0*.mp4
  • *.s0*e0*.avi
  • *.s0*e0*.mkv
  • counterstrike*
  • counter strike*
  • quicktime*.exe
  • quicktimeinstaller.exe

并且它们都有效但当我找到并尝试删除dvdrip*.avi*dvdrip*(如电影)时,它会找到该文件但不删除它。

我在具有管理员权限的文件服务器上运行脚本。

这是剧本:

cls

set-executionpolicy remotesigned -scope CurrentUser -force

Age of file Not using at the moment!!
#$oldTime = [int]30 # 30 days
# Workin dir
Set-Location # set your working location
#hostname for Log
$hname = hostname 
#For multiple drives
$path = Get-Content "pathlist.txt"
#File extensions
$skrar = Get-Content "files.txt"
$files = Get-ChildItem -Path $path -Recurse -Include $skrar # | WHERE {($_.CreationTime -le $(Get-Date).AddDays(-$oldTime))}
#For log(calcs the total size of deleted files)
$filesum = 0
#For log(calcs the total size of deleted folders) 
$foldersum = 0
#check for log dir
if(!(Test-Path -Path c:\Fileserverclean_log\)){
New-Item c:\Fileserverclean_log -type directory
}
#log path
$LogHome = "c:\Fileserverclean_log"
#Log time
$logtime = Get-Date -Format "dd-MM-yyyy_HH-mm-ss"
#Log filename
$logfile = $LogHome + "del_" + $logtime + ".log"
#Log File Message
"$logtime Byrjar Hreynsun á: $hname"  | Out-File $logfile -Append -Force
"----------------------------------" | Out-File $logfile -Append -Force

#File delete
foreach ($file in $files) {

    $Foldersize = Get-ChildItem $file -Recurse | Measure-Object -Property length -Sum

    if($file.Attributes -eq "Archive"){
    $File.fullname + "    stærð: " + "{0:N2}" -f ($file.length/1MB) + " MB" | Out-File $logfile -Append
    $filesum += [int]($file.Length)
    }

    else{
    $File.fullname + "    stærð: " + "{0:N2}" -f ($foldersize.sum/1MB) + " MB" | Out-File $logfile -Append
    $Foldersum += [int]($Foldersize.Sum)
    }

    # info on operation
    Write-Host "Deleting files!....path $File" -ForegroundColor Red
    #$file.Delete()
    Remove-Item $file.Name -Force -Recurse
    }
    $logtimeend = Get-Date -Format "dd-MM-yyyy_HH-mm-ss"
    "" | Out-File $logfile -Append -Force
    "" | Out-File $logfile -Append -Force
    "$logtimeend Hreynsun Lokið á: $hname" | Out-File $logfile -Append -Force

    $Totalfilesize = $filesum + $foldersum
    "" | Out-File $logfile -Append -Force
    "" | Out-File $logfile -Append -Force
    "Eytt í heild: " + "{0:N2}" -f ($Totalfilesize/1MB) + " MB" | Out-File $logfile -Append -Force
    "              ---------" | Out-File $logfile -Append -Force
    #"Eytt í heild ($Totalfilesize/1MB)" | Out-File $logfile -Append -Force
    Send-MailMessage -To xxxxx@xxxxxx.com -From cleaner@someemail.com -Subject "Cleaning log from $hname" -SmtpServer mail.something.com -Attachments $logfile

我希望我已经说清楚了。如果没有,请告诉我。

更新

我尝试了$ file.delete,这很有效。我应该使用它而不是删除项吗?

0 个答案:

没有答案