harris9050
harris9050

Reputation: 21

Deleting unwanted files and folders using a Powershell script

I'm a newcomer to Powershell and I've been playing around with some basic commands in the console, I now want to try to further my skills and create a script that will do some basic tasks for me.

On my PC I have a lot of unwanted files and folders.

I have multiple files named 'program.exe' which exist in different directories and I also have a file called 'info.pdf' which exists in multiple different folders.

How can I go about programming a script to delete the files with that specific name and extension and also delete the directory that the file is present is in also, I was looking into using the -Recursive parameter but don't want it to delete anything it shouldn't by accident.

Currently, these are the commands I have been trying to use in the PowerShell script

Get-Location
$targetdirectory = /*


Get-ChildItem *program.exe 
Get-ChildItem *info.pdf

Remove-Item /program.exe
Remove-Item /info.pdf

I'm a bit unsure about the syntax and what order to place these commands in for it to be successful, If I want my script to look in the current directory and other directories do I simply use = /*?

And how can I go about the script deleting those specific file names and then deleting the folder it exists in.

Thanks!

Upvotes: 0

Views: 1231

Answers (1)

PMental
PMental

Reputation: 1179

First you'll definitely need the -Recurse parameter. Secondly Remove-Item supports the -WhatIf parameter, but not all CmdLets do, so it's a good habit to check you selection first (run the first line, then check $FilesToRemove, then run the second line):

$FilesToRemove = Get-ChildItem /* -Include 'program.exe','info.pdf' -Recurse -ErrorAction Ignore
Remove-Item -Path $FilesToRemove -WhatIf

Remove the -WhatIf to do the actual deleting. If your files are under a specific path you could use substitute with eg. /home/*, just make sure you end any path with /*.

Upvotes: 1

Related Questions