Powershell script to delete a file

1.Need a powershell script to delete two files  (channel.ks and security.csp) in a particular location

first need to check the files are present in the location..if so delete them else exit

2.Need a powershell script to delete this folder c:\program files\agent

Need to check whether  folder exists in the path..if so delete else exit
Suresh KumarAsked:
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.

johnsoneSenior Oracle DBACommented:
I have more expertise in Unix scripting, but this seems to work in PowerShell.
if (Test-Path "$FilePath\channel.ks")
    Remove-Item -path "$FilePath\channel.ks"
if (Test-Path "$FilePath\security.ksp")
    Remove-Item -path "$FilePath\security.ksp"
if (Test-Path "c:\program files\agent")
    Remove-Item -path "c:\program files\agent" -recurse

Open in new window

You need to set the variable on the first line to the directory where the 2 files exist.  If they exist and you have permission to remove them, they should be removed.  Same thing with the directory (everything in the directory will be removed, if anything is there).  You probably need to run PowerShell as administrator to remove the directory.

You also need to have an execution policy set up to run scripts on your system.
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Usually it is much simpler to just ignore the error raised if the file is not there:
Remove-Item C:\Temp\channel.ks -ea SilentlyContinue
Remove-Item C:\Temp\security.ksp -ea SilentlyContinue

Open in new window

as you do not want to do anything specific in case they do not exist.
This is another way, which allows for rasing (error) exceptions e.g. because of file locks or missing privleges:
Get-Item C:\Temp\channel.ks, C:\Temp\security.ksp -ea SilentlyContinue | Remove-Item -force
Get-Item 'c:\program files\agent'  -ea SilentlyContinue | Remove-Item -recurse -force

Open in new window

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