Remove specific files in a folder using Powershell that don't contain a word

Remove specific files in a folder using Powershell that don’t contain a word

Following on from the following post:
Remove specific files in a folder using powershell

Is it possible to do the opposite to this.

I have files in a folder that are called by the date and time of when it was created i.e 01_01_2022, 02_01_2022, 03_01_2022 and so on. However, there is also a file with the same name but with the word large at the end i.e 01_01_2022_large, 02_01_2022_large, 03_01_2022_large. Is it possible in Powershell to remove the files that DON’T have the word large in the file name. I can only find when it DOES contain the word.

>Solution :

Yes, it is possible to do this in PowerShell. You can use the Get-ChildItem cmdlet to get a list of all the files in a folder, and then use the Where-Object cmdlet to filter the list of files to only include those that do not have the word "large" in their file name.

# Get a list of all the files in the folder
$files = Get-ChildItem -Path <path to folder>

# Filter the list of files to only include those that do not have the word "large" in their file name
$files = $files | Where-Object {$_.Name -notmatch "large"}

# Remove the remaining files from the folder
$files | Remove-Item

Leave a Reply