Nicole
Nicole

Reputation: 13

How do I automatically answer “yes” in Powershell?

How do I automatically answer “yes” to a prompt in Powershell?

Write-Host "Deleting all files and subfolders..."
Get-ChildItem -Path C:\Users\333\Downloads -Recurse | Remove-Item
Get-ChildItem -Path C:\Users\333\Desktop -Recurse | Remove-Item
Get-ChildItem -Path C:\Users\333\Documents -Recurse | Remove-Item
Clear-RecycleBin -Force
Write-Host "Done!"

Upvotes: 0

Views: 2176

Answers (1)

mklement0
mklement0

Reputation: 439932

In order to avoid a confirmation prompt when using Remove-Item to delete a non-empty directory:

  • you need the -Recurse switch
  • additionally, if the directory contains hidden items, you need the -Force switch.
  • (If the $ConfirmPreference preference variable has been changed from its default, 'High', you'll also need -Confirm:$false)

In short:

  • Remove-Item -Recurse -Force $someDirectory quietly removes directory $someDirectory itself (invariably with all its contents)

  • Remove-Item -Recurse -Force $someDirectory\* removes just its contents (along with any subdirectories, recursively).

Caveat: In earlier Windows versions, before Windows 10 20H2, file removal is inherently asynchronous, which means that such recursive calls sometimes fail - see this answer.


Therefore, you don't even need Get-ChildItem in your case - just use Remove-Item to remove the content of the target directories, (which includes an subdirectories) - by appending wildcard expression \* - which you can even do with a single call, given that arrays of input paths are supported.

In the context of your original code:

Write-Host "Deleting all files and subfolders..."
Remove-Item -Recurse -Force -Path C:\Users\333\Downloads\*, C:\Users\333\Desktop\*, C:\Users\333\Documents\* 
Clear-RecycleBin -Force
Write-Host "Done!"

Upvotes: 2

Related Questions