Using PowerShell, is it possible to remove some directory that contains files without prompting to confirm action?
14 Answers
From PowerShell remove force answer: help Remove-Item says:
The Recurse parameter in this cmdlet does not work properly
The command to workaround is
Get-ChildItem -Path $Destination -Recurse | Remove-Item -force -recurse
And then delete the folder itself
Remove-Item $Destination -Force
2018 Update
In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName
to silently delete the directory .\DirName
with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.
rm -Force -Recurse -Confirm:$false $directory2Delete
didn't work in the PowerShell ISE, but it worked through the regular PowerShell CLI.
I hope this helps. It was driving me bannanas.
Below is a copy-pasteable implementation of Michael Freidgeim's answer
function Delete-FolderAndContents {
# http://stackoverflow.com/a/9012108
param(
[Parameter(Mandatory=$true, Position=1)] [string] $folder_path
)
process {
$child_items = ([array] (Get-ChildItem -Path $folder_path -Recurse -Force))
if ($child_items) {
$null = $child_items | Remove-Item -Force -Recurse
}
$null = Remove-Item $folder_path -Force
}
}
$LogPath = "E:\" # Your local of directories
$Folders = Get-Childitem $LogPath -dir -r | Where-Object {$_.name -like "*grav*"} # Your keyword name directories
foreach ($Folder in $Folders)
{
$Item = $Folder.FullName
Write-Output $Item
Remove-Item $Item -Force -Recurse -ErrorAction SilentlyContinue
}
If you want to concatenate a variable with a fixed path and a string as the dynamic path into a whole path to remove the folder, you may need the following command:
$fixPath = "C:\Users\myUserName\Desktop"
Remove-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
In the variable $newPath
the concatenate path is now: "C:\Users\myUserName\Desktop\Folder\SubFolder"
So you can remove several directories from the starting point ("C:\Users\myUserName\Desktop"
), which is already defined and fixed in the variable $fixPath
.
$fixPath = "C:\Users\myUserName\Desktop"
Remote-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder1") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder2") -Recurse