Remove-Item not removing from task scheduler

I have a script to backup the SQL database, and to delete everything from a folder older than 7 days. I have this as a Windows task scheduler.

The task scheduler backups the database, and adds the new .bak file at the right folder. But its not deleting the files that are over 7 days.

If I open PowerShell and run this script manually, it deletes files over 7 days. So what’s keeping task scheduler from doing everything but Remove-Item -Recurse -Confirm:$false

#Create Variables
$Server = "REI-Epicor-DB"
$Database = "EpicorERP"
$BackupFolder = "H:\MSSQL\Backup"
$DT = Get-Date -Format MM-dd-yyyy
$FilePath = "$($BackupFolder)\$($Database)_db_$($dt).bak"

#Backup SQL database to $BackupFolder
Backup-SqlDatabase -ServerInstance $Server -Database $Database -BackupFile $FilePath


# Delete everything older than 7 days in $BackupFolder
$Daysback = "-7"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $BackupFolder | ? {$_.LastWriteTime -lt $DatetoDelete} | Remove-Item -Recurse -Confirm:$false

I suspect its because its confirming the deletion of files.
But when I do it manually, it does not ask for confirmation, that’s why I have -Confirm:$false

Why do you use the parameter -Recurse? Did you try the parameter -Force?

@Olaf

I used -Recurse to remove all sub folders, but I don’t need that now since I cleared it up.
For some reason the -Force was not generating, but I have it there now.

Get-ChildItem $BackupFolder | ? {$_.LastWriteTime -lt $DatetoDelete} | Remove-Item -Confirm:$false -Force

Hmmm … I’m confused. Did that solve your issue?