How can I delete files with PowerShell without confirmation?

前端 未结 7 1868
暗喜
暗喜 2021-01-11 11:56

I am trying to get the below PowerShell script to work using Task Scheduler. The problem is that it wont delete any files.

When I run it manually it needs a confirma

相关标签:
7条回答
  • 2021-01-11 12:53

    You can simplify your script like it:

    1. Use -file with Get-Childitem command
    2. Not necessary to have a $Now variable
    3. Use alias for your where (better visibility)
    4. Your if must be out for check if no files
    5. Add -Force to your Remove-Item command
    6. Extension are not necessary if you use '\*.*'

    Code ratified:

    $Days = "10"
    #----- define folder where files are located ----#
    $TargetFolder = "D:\Shares\Downloads\TV\AutoDL"
    #----- define LastWriteTime parameter based on $Days ---#
    $LastWrite = (Get-Date).AddDays(-$Days)
    
    #----- get files based on lastwrite filter and specified folder ---#
    $Files = Get-Childitem $TargetFolder -Recurse -file | Where LastWriteTime -le "$LastWrite"
    
    if ($Files -eq $null)
    {
        Write-Host "No more files to delete!" -foregroundcolor "Green"
    }
    else
    {
       $Files | %{
       write-host "Deleting File $_" -ForegroundColor "DarkRed"
       Remove-Item $_.FullName -Force   | out-null
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题