0

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!

1

1 Answer 1

1

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 /*.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much for your guidance, it's been a huge help. If I'm not on a Windows PC and using Mac can I simply do "*" or do I still need to include the 'C:' bit equivalent for mac before, I'm aware Mac doesn't use C and it just uses /home/ etc... but will just using "*" be able to work as well?
@harris9050 Sorry yes, missed that part. Just subtitute it woth /*and it should work. I'll update the answer.

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.