0

I am trying to write a script in Powershell to remove some files automatically with a certain file name.

My idea is to get all the folders in the directory, then loop through the subdirectory, and remove all items with the file name, but it doesn't seem to be working as expected.

Here is my script


$folders = Get-ChildItem -path "C:\Website-Backup" -Recurse | Where-Object {$_.PsIsContainer} |Group-Object {$_.FullName.Split('_')[0] }
$subfolders = Get-ChildItem -path $folders -Recurse | Where-Object {$_.PsIsContainer} | Group-Object {$_.FullName.Split('_')[0] }

ForEach($subfolder in $subfolders)
{
    Remove-Item * -Include *100x*
}

Any idea why the script doesn't seem to be doing anything?

2 Answers 2

2

I think you can simplify your code if I understand correctly to:

Get-ChildItem "C:\Website-Backup" -Recurse  -include "*100x*" -file | remove-item
Sign up to request clarification or add additional context in comments.

Comments

1

The Group-Object command is likely what's confusing things here - Remove-Item is expecting a path - you're not referencing the subfolder variable in your loop as well, so this is the same as just running the Remove-Item command as many times as there are items in the array.

You can try this instead;

Get-ChildItem -Path "C:\Website-Backup" -Recurse | Where-Object -FilterScript { $_.name -like 'MyFile.txt' } | Remove-Item

This will pipe the returned child items into Where-Object, filter it to the specified file name, then pass that to Remove-Item as a file path.

You can also skip the Where-Object, but you lose a bit of control this way;

Get-ChildItem -Path 'C:\WebSiteBackup\*MyFile.txt' -Recurse | Remove-Item

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.