powershell - 删除未锁定(正在使用)的文件

标签 powershell delete-file filelock

我正在尝试删除%TEMP%中超过30天的所有文件(不是文件夹)。问题是程序正在使用某些文件,因此无法删除它们。我尝试解决以下问题:

   function IsFileLocked($filePath){
        #write-host $filePath

        Rename-Item $filePath $filePath -ErrorVariable errs -ErrorAction SilentlyContinue
        $errs.Count
        if ($errs.Count -ne 0)
        {
            return $true #File is locked
        }
        else 
        {
            return $false #File is not locked  
        }
    }

 $Path= "$env:temp"
    if ((Test-Path -Path $Path) -ieq $true) 
    {
    $Daysback =  '-30'
    $CurrentDate = Get-Date
    $DatetoDelete = $CurrentDate.AddDays($Daysback) 

    get-childitem $Path -recurse  | Where-Object {$_.LastWriteTime  -lt $DatetoDelete } | 
    Where-Object {$_.PSIsContainer -eq $False }| Where-Object {(IsFileLocked -filePath "($_)") -eq $false }# | remove-item   -force #-WhatIf
    }

问题是(IsFileLocked -filePath "($_)") -eq $false不返回任何元素。
get-childitem是否有可能阻止文件,从而在我运行get-childitem时将它们全部锁定?

还有其他想法如何解决这个问题?

最佳答案

如何删除30天以上的文件并忽略错误:

$old = (Get-Date).AddDays(-30)

Get-ChildItem $env:TEMP -Recurse | 
Where-Object {!$_.PSIsContainer -and $_.LastWriteTime -lt $old } | 
Remove-Item -Force -ErrorAction SilentlyContinue

关于powershell - 删除未锁定(正在使用)的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12371836/

相关文章:

python - Django 发送邮件 "lock already in place. quitting."

PowerShell stderr 重定向到文件插入换行符

php - Laravel 5 文件删除错误

java - 在 JUnit 中删除文件和目录

c# - 带有锁定文件的 FileStream

python - 为什么 Python filelock 库在 Windows 而不是 UNIX 上删除锁定文件?

c# - 将 PowerShell 参数传递给 Process.Start

powershell - 如何通过管道将多个文件放入Copy-Item并保持目录结构?

powershell - 在Powershell中使用itextsharp从PDF提取页面

android - 获取文件创建时间