I have a folder where I need to delete all files and folders except a small list of files and folders.
I can already exclude a list of files, but don't see a way to exclude a folder and its contents.
Here is the folder structure:
|-C:\temp \-C:\temp\somefile.txt \-C:\temp\someotherfile.txt | |-C:\temp\foldertodelete \-C:\temp\foldertodelete\file1.txt | |-C:\temp\foldertokeep | \-C:\temp\foldertokeep\file2.txt
I want to keep somefile.txt and the folder foldertokeep and its content.
This is what I have right now:
Get-ChildItem -Path 'C:\temp' -Recurse -exclude somefile.txt | Remove-Item -force -recurse
This really does not delete somefile.txt. Is there a way to exclude folder foldertokeep and its content from the delete list?
To get only directories, use the Directory parameter and omit the File parameter. To exclude directories, use the File parameter and omit the Directory parameter, or use the Attributes parameter. To get directories, use the Directory parameter, its "ad" alias, or the Directory attribute of the Attributes parameter.
In the search box (top right), type NOT kind:folder . You will now see a list of all files in your current folder and all its subfolders. Use Control-A to select all the files. Now you can move them all to another folder.
Select multiple files or folders that are not grouped together. Click the first file or folder, and then press and hold the Ctrl key. While holding Ctrl , click each of the other files or folders you want to select.
Get-ChildItem -Path 'C:\temp' -Recurse -exclude somefile.txt | Select -ExpandProperty FullName | Where {$_ -notlike 'C:\temp\foldertokeep*'} | sort length -Descending | Remove-Item -force
The -recurse switch does not work properly on Remove-Item (it will try to delete folders before all the child items in the folder have been deleted). Sorting the fullnames in descending order by length insures than no folder is deleted before all the child items in the folder have been deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With