Delete all CSV files except for 1 specifid CSV file

Member_2_5306354
Member_2_5306354 used Ask the Experts™
on
I would like to use a simple script  to delete all *.csv files found in C:\Temp1\...  except for one file called Output.csv

It would be in Batch, .ps1 or vbs..

Thanks in advance.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
In test mode; remove the -WhatIf to run it for real:
Get-ChildItem C:\Temp1 -Filter *.csv | Where-Object {$_.BaseName -ne 'output'} | Remove-Item -Force -WhatIf

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
For the fun of it, here's a cmd.exe version, for immediate execution in a command prompt.
As before in test mode; remove the uppercase ECHO to run it for real:
for %a in ("C:\Temp1\*.csv") do @(if /i not "%~na"=="Output" ECHO del "%~a")

Open in new window

For a batch script, double up on those percent signs of the loop variable:
for %%a in ("C:\Temp1\*.csv") do @(if /i not "%%~na"=="Output" ECHO del "%%~a")

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You can do it in one - but a potentially safer method would be to break your script into 3 parts
1. Rename the file to .preserve
2. Remove all .csv files
3. Rename the file back again

This has the added advantage that your delete does not have to be updated if names change or you want to expand to include additional names.

Author

Commented:
Thanks very much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial