A file remover function in PowerShell

Here’s a simple function in PowerShell that allows you to remove any non-locked files, by specifying: paths and file types.

function remove-Files() {

Param (

[string] $targetPth, 
[string[]] $fileTypes, 
[string] $errAct 

)

if ($fileTypes.Length -gt 0) { 

try {
 
if ((Get-ChildItem $targetPth | Measure-Object).Count -eq 0) { 

Throw "Error: Folder is empty." 

}

Get-ChildItem $targetPth -Include $fileTypes -Recurse -ErrorAction $errAct | Remove-Item -Recurse -Force 

}
catch [System.Exception] {  

"Oops! Something happened." 

}
finally {

$Error.Clear() 

}

}
else { 

try { 

if ((Get-ChildItem $targetPth | Measure-Object).Count -eq 0) { 

Throw "Error: Folder is empty." 

}

Get-ChildItem $targetPth -Recurse | Remove-Item -Recurse -Force 

} 
catch [System.Exception] {  

"Oops! Something happened." 

}

finally { 

$Error.Clear() 

}
}
}
}


Function accepts 3 parameters: [string] $targetPth, [string[]] $fileTypes and [string] $errAct.

You can pass a root folder, and pass an array of filetypes, for example: .txt, .pdf, .log, .tmp etc. to have the function attempt file removal.

Best used in situations where you need to target specific files that take up a lot of space and when you need to run the whole thing silently, behind the scenes.

0
Capture objects and export them using PowerShell Offload your powershell code

No Comments

No comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *