Last active
February 12, 2026 10:54
-
-
Save mlocati/6ded17c0a4ef8c7cd2c6b98aa041c4ac to your computer and use it in GitHub Desktop.
rm -rf in PowerShell/pwsh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .DESCRIPTION | |
| Deletes the specified file or directory (recursively) if it exists. | |
| .PARAMETER Path | |
| The path of the file or directory to delete. | |
| .OUTPUTS | |
| System.Boolean. $false if something existed but could not be removed, $true otherwise. | |
| .NOTES | |
| This is highly inspired by the 'rm -rf' command in Unix-like systems. | |
| #> | |
| function rmrf { | |
| [OutputType([bool])] | |
| [CmdletBinding(SupportsShouldProcess = $true)] | |
| Param( | |
| [Parameter(Mandatory, ValueFromPipeline, ValueFromRemainingArguments)] | |
| [string[]]$Path | |
| ) | |
| $allSucceeded = $true | |
| foreach ($p in $Path) { | |
| $items = Get-Item -LiteralPath $p -ErrorAction SilentlyContinue | |
| if (-not $items) { | |
| $items = Get-ChildItem -Path $p -Force -ErrorAction SilentlyContinue | |
| if (-not $items) { | |
| Write-Verbose "No items found at path: $p" | |
| continue | |
| } | |
| } | |
| foreach ($item in $items) { | |
| try { | |
| if ($item -is [System.IO.FileSystemInfo] -and $null -ne $item.LinkTarget) { | |
| Write-Verbose "Removing symbolic link $($item.FullName)" | |
| if ($PSCmdlet.ShouldProcess($item.FullName, 'Remove')) { | |
| Remove-Item -LiteralPath $item.FullName -Force -ErrorAction Stop | |
| } | |
| } | |
| elseif ($item.PSIsContainer) { | |
| Write-Verbose "Removing directory $($item.FullName) recursively" | |
| if ($PSCmdlet.ShouldProcess($item.FullName, 'Remove')) { | |
| Remove-Item -LiteralPath $item.FullName -Recurse -Force -ErrorAction Stop | |
| } | |
| } | |
| else { | |
| Write-Verbose "Removing file $($item.FullName)" | |
| if ($PSCmdlet.ShouldProcess($item.FullName, 'Remove')) { | |
| Remove-Item -LiteralPath $item.FullName -Force -ErrorAction Stop | |
| } | |
| } | |
| if (Test-Path -LiteralPath $item.FullName) { | |
| Write-Verbose "Failed to remove $($item.FullName)" | |
| $allSucceeded = $false | |
| } | |
| } | |
| catch { | |
| Write-Verbose "Error removing $($item.FullName): $_" | |
| $allSucceeded = $false | |
| } | |
| } | |
| } | |
| return $allSucceeded | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Location of that file? Open a powershell terminal and enter
$profile: