Link to home
Start Free TrialLog in
Avatar of Rothbard
RothbardFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Delete a set of files

I just posted a similar question. I need a script which deletes all files EXCEPT those whose names are included in a text file (e.g. nodelete.txt). I would be very grateful if someone could help me with this.
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

Powershell solution:
 $files2Exclude=Get-Content .\nodelete.txt : Remove-Item * -Exclude $files2Exclude

Open in new window

not as elegant
---
@echo off
set source=C:\30092014
for /f "Tokens=* Delims=" %%x in (list.txt) do copy %%x %temp%
del %source%\* /q
for /f "Tokens=* Delims=" %%x in (list.txt) do copy %temp%\%%x %temp% %source%
---
ASKER CERTIFIED SOLUTION
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Better late then never ;)

@echo off
set source=C:\30092014

for /f "tokens=*" %%G in ('dir /b /a-d "%source%\*"') do (call :del_proc "%%G")
GOTO :eof
:del_proc
findstr -sip %1 list.txt > NULL
IF  ERRORLEVEL 1  del %1

Open in new window

Avatar of Rothbard

ASKER

Thanks but it doesn't seem to work. I get the following error message:

Get-Content : A positional parameter cannot be found that accepts argument ':'.
At line:1 char:27
+ $files2Exclude=Get-Content <<<<  .\nodelete.txt : Remove-Item * -Exclude $files2Exclude
    + CategoryInfo          : InvalidArgument: (:) [Get-Content], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
You need to give full path to the file or run it in the folder where's that file.
Thanks!
The easier you make the code to read the better off you are down the road when you look at the code a year or so from now.  Comments are always good
 $files2Exclude=Get-Content .\nodelete.txt
 Remove-Item * -Exclude $files2Exclude

Open in new window

$files2exclude = Read-Host "Please Enter the Path and File name of the Files to Exclude List"
if ((test-path $filestoexclude) -eq $false ) 
    {
    $output = $files2exclude + "Does Not Exist!"
        Write-output $output
     }
else {
    $filepath = read-host "Please Enter the Path of the files to delete"
    if ((test-path $filepath) -eq $false ) {
         $output = $filespath + "Does Not Exist"
         Write-output $output
         }
    else {
     #
     #assumes that you are on the same drive
     #
     cd $filepath
     Remove-Item * -Exclude $files2exclude
     }
}       

Open in new window