Created
December 21, 2024 15:14
-
-
Save iamliuzy/19731ce1c7e82c98361eb537693f42d3 to your computer and use it in GitHub Desktop.
A Powershell script to remove files with specific patterns in a target directory.
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: | |
# A script to remove files with specific patterns in a target directory. | |
# | |
# Usage: | |
# 1. Change line 10-11 properly according to the instruction beside them. | |
# 2. Run the script in PowerShell. | |
# Tips: | |
# - Change "$false" to "$true" in line 6 to show the files to be deleted. | |
# This won't actually delete them. | |
# - Use "*" in pattern strings to match any text. | |
# e.g. "*abc*" matches "abc", "abc123", "123abc", etc. | |
# Arguments | |
$targetPath = "<target directory path>" | |
# Change the text in the quotes to the target directory path | |
$patterns = @("example.txt") | |
# Add or remove pattern strings to match the files you want to remove | |
$debugMode = $false | |
# Change to $true to show the files to be deleted without actually deleting them | |
# Code | |
try { | |
$originalLocation = Get-Location | |
Set-Location -Path $targetPath | |
foreach ($pattern in $patterns) { | |
$files = Get-ChildItem -Path $targetPath -Filter $pattern -Recurse -ErrorAction SilentlyContinue | |
if ($null -ne $files) { | |
if ($debugMode) { | |
Write-Host "Files to be deleted:" | |
foreach ($file in $files) { | |
Write-Host "$file" | |
} | |
} | |
else { | |
Remove-Item -Force -Recurse -Path $files -ErrorAction SilentlyContinue | |
} | |
} | |
} | |
} catch { | |
Write-Error "An error occurred: $_" | |
} finally { | |
Set-Location -Path $originalLocation | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script was written with the help of Github Copilot.