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

Viewed 4855

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

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.

Related