Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete files with PowerShell without confirmation?

Tags:

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 confirmation before deleting files.

Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want  to continue? [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): 

How can I edit this script to delete files without any confirmation so I can run it using Task Scheduler?

#----- define parameters -----# #----- get current date ----# $Now = Get-Date #----- define amount of days ----# $Days = "10" #----- define folder where files are located ----# $TargetFolder = "D:\Shares\Downloads\TV\AutoDL" #----- define extension ----# $Extension = "*.*" #----- define LastWriteTime parameter based on $Days ---# $LastWrite = $Now.AddDays(-$Days)  #----- get files based on lastwrite filter and specified folder ---# $Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}  foreach ($File in $Files)  {     if ($File -ne $NULL)     {         write-host "Deleting File $File" -ForegroundColor "DarkRed"         Remove-Item $File.FullName | out-null     }     else     {         Write-Host "No more files to delete!" -foregroundcolor "Green"     } } 
like image 878
ProphetSe7en Avatar asked Apr 25 '17 12:04

ProphetSe7en


People also ask

How do I delete files without confirmation?

Right-click the Recycle Bin icon that is loaded onto your desktop by default and select Properties from the context menu. You should see something like Figure A. From that page you can toggle the delete confirmation by checking or unchecking the checkbox.

How do I bypass confirmation in PowerShell?

If the script uses Powershell cmdlets, you can specify -Confirm:$false to suppress the prompt.


2 Answers

Remove-Item foldertodelete -Recurse -Force -Confirm:$false 

works for me.

like image 166
user11431789 Avatar answered Sep 22 '22 11:09

user11431789


You need to add -Confirm:$false to the Remove-Item command to override the default confirmation behaviour. Failing that, try adding -Force.

like image 43
Mark Wragg Avatar answered Sep 18 '22 11:09

Mark Wragg