Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
    
You may be looking for alias. – Mast May 11 '15 at 9:55
1  
@Mast, an alias is just an alternative name for a command. You can't specify parameters or anything in an alias definition. – Dangph May 12 '15 at 0:53
up vote 6 down vote accepted

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
            }
        }
    }
}
share|improve this answer
    
7th line from bottom, typo: "P" should be "{". Which doesn't lessen that perfect function. – user1016274 Sep 13 '15 at 18:40
    
@user1016274 thanks, fixed! – briantist Sep 13 '15 at 18:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.