Powershell if file exist delete it

Hi as the title suggests  what do i need to do this

I have a failry large powershell script that i need to edit (I dont know powershell :-) )

and i need a line or two that will see if a short cut exists in a folder and if it does delete it.

please help

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Hi there,

I am fairly new to PowerShell myself, and this will be my first contribution to Experts-Exchange.  I don't claim this is the best solution, but I have tested it and it seems to do what you asked.  Here is the code:

$t = "F:\Sandbox\Debug - Shortcut.lnk"
$e = Test-Path $t
if ( $e -eq $true ) { rm $t }
else { Write-Host "Shortcut does not exist." }

You would substitute in your path in the first line and you can delete the last line if you don't need to respond to the condition where the file doesn't exist.  The Test-Path is a PowerShell cmdlet which tests for the existence of a file or path.  The cmdlet returns “True” or “False” depending on whether the file or path exists.  $true and $false are built-in variables for testing true/false conditions.  The rm will delete the file if the folder or path in the variable $t exists.  The –eq is just PowerShell’s version of testing for equality, say myVar = “someValue” in other languages.  Hope this helps.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chris DentPowerShell DeveloperCommented:

Welcome to EE Jason :)

You can do an implicit boolean condition there, a very small modification to the code above:

$Path = "F:\Sandbox\Debug - Shortcut.lnk"
If (Test-Path $Path) { Remove-Item $Path }

It makes no real difference, just less typing :)

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.