HiveBrain v1.2.0
Get Started
← Back to all entries
patternshellCritical

Delete folder if it exists in PowerShell

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
powershellfolderdeleteexists

Problem

In my PowerShell script I'm trying to delete a folder, but only if it exists:

if (Test-Path $folder) { Remove-Item $folder -Recurse; }


I find myself repeating this combination of cmdlets quite a few times, and wished I had something like this:

# Pseudo code:
Remove-Item $folder -Recurse -IgnoreNonExistentPaths


Is there a way to do something like that? A different command, or an option I've missed from the Remove-Item documentation perhaps? Or is the only way to DRY out this bit of code to write my own cmdlet that combines Test-Path and Remove-Item?

Solution

I assume you're just trying to avoid the error message in case it doesn't exist.

What if you just ignore it:

Remove-Item $folder -Recurse -ErrorAction Ignore


If that's not what you want, I would recommend writing your own function:

function Remove-ItemSafely {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)]
[String[]]
$Path ,

[Switch]
$Recurse
)

Process {
foreach($p in $Path) {
if(Test-Path $p) {
Remove-Item $p -Recurse:$Recurse -WhatIf:$WhatIfPreference
}
}
}
}

Context

StackExchange Code Review Q#90372, answer score: 90

Revisions (0)

No revisions yet.