Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Delete everything else except one file in root and one in sub folder

I need to delete all files and folders except one file in root folder and one other file in sub folder. Furthermore file names are passed as an argument to the script as comma sep1rated string like 'file1.txt,Subfolder\file2.txt'.

I was trying to do something like this,

$Path = "C:\\Delete\\"
$Argument= "file1.txt,Subfolder\\file2.txt"
$ExcludedFiles = [string]::Join(',', $Argument);
$files = [System.IO.Directory]::GetFiles($Path, "*", "AllDirectories")
    
foreach($file in $files) { 
    $clearedFile = $file.replace($Path, '').Trim('\\');
                
    if($ExcludedFiles -contains $clearedFile){
        continue;
    } 
            
    Remove-Item $file
}

By doing this all the folders remain and all the files get deleted. Can any one please suggest that how should I try to do this since I am having difficulty in doing this.

like image 877
Haiyan Jamali Avatar asked Oct 23 '25 14:10

Haiyan Jamali


1 Answers

The easiest way to get it done is using the -Exclude paramater in get-childitem.

Here are the examples to Exclude a file:

Get-ChildItem C:\Path -Exclude SampleFileToExclude.txt| Remove-Item -Force

Exclude files with a specific extension using wildcard:

Get-ChildItem C:\Path -Exclude *.zip | Remove-Item -Force

Get all the files recursively and exclude the same:

Get-ChildItem C:\Path -Recurse -Exclude *.zip | Remove-Item -Force

Exclude list of items as per your wish in the same command:

Get-ChildItem C:\Path -Recurse -Exclude *.zip, *.docx | Remove-Item -Force

You can even use with array and where condition:

$exclude_ext = @(".zip", ".docx")
$path = "C:\yourfolder"
Get-ChildItem -Path $path -Recurse | Where-Object { $exclude_ext -notcontains $_.Extension }

And then you can remove using Remove-Item

Hope it helps.

like image 135
Ranadip Dutta Avatar answered Oct 26 '25 04:10

Ranadip Dutta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!