PowerShell Delete everything else except one file in root and one in sub folder
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.
Delete all files and folders but exclude a subfolder
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.
Windows batch script to delete everything in a folder except one
You could try to hide the folders before the for-loop, and unhide them afterwards, like this:
ATTRIB +H D:\myfolder\keepit
FOR /D %%i IN ("D:\myfolder\*") DO RD /S /Q "%%i" DEL /Q "D:\myfolder\*.*"
ATTRIB -H D:\myfolder\keepit
How to delete everything in a folder except one or two folders that I want to retain?
You can use the os module
to loop through every item and folder in your directory and delete them. You could also define a list with specific items (like your folder names) to prevent them from being deleted. Keep in mind that if you want to keep files from being removed, you also have to add their format (like ".txt" for a text file).
As usual, be careful when deleting files. Maybe you want to add a check before the os.remove()
or maybe replace it with a print statement first (print(item)
) so that you see what is being removed.
import os # Import the os module
working_directory = r"C:\Users\Vishwesh\Folder1"
retain = ["Folder11", "Folder12", "file1.txt", "file2.txt"]
os.chdir(working_directory) # Change directory to your folder
# Loop through everything in folder in current working directory
for item in os.listdir(os.getcwd()):
if item not in retain: # If it isn't in the list for retaining
os.remove(item) # Remove the item
How to delete all files in folder except CSV?
import os
directory = "/path/to/directory/with/files"
files_in_directory = os.listdir(directory)
filtered_files = [file for file in files_in_directory if not file.endswith(".csv")]
for file in filtered_files:
path_to_file = os.path.join(directory, file)
os.remove(path_to_file)
first, you list all files in directory. Then, you only keep in list those, which don't end with .csv. And then, you remove all files that are left.
Delete all in folder except the filename in list
You could try,
public void DeleteFilesExcept(string directory,List<string> excludes)
{
var files = System.IO.Directory.GetFiles(directory).Where(x=>!excludes.Contains(System.IO.Path.GetFileName(x)));
foreach (var file in files)
{
System.IO.File.Delete(file);
}
}
Make .gitignore ignore everything except a few files
An optional prefix
!
which negates the pattern; any matching file excluded by
a previous pattern will become included again. If a negated pattern matches,
this will override lower precedence patterns sources.
# Ignore everything
*
# But not these files...
!.gitignore
!script.pl
!template.latex
# etc...
# ...even if they are in subdirectories
!*/
# if the files to be tracked are in subdirectories
!*/a/b/file1.txt
!*/a/b/c/*
delete all directories except one
With bash
you can do this with the extglob
option of shopt
.
shopt -s extglob
cd parent
rm -rf !(four)
With a posix shell I think you get to use a loop to do this
for dir in ./parent/*; do
[ "$dir" = "four" ] && continue
rm -rf "$dir"
done
or use an array to run rm
only once (but it requires arrays or using "$@"
)
arr=()
for dir in ./parent/*; do
[ "$dir" = "four" ] && continue
arr+=("$dir")
done
rm -rf "${arr[@]}"
or
for dir in ./parent/*; do
[ "$dir" = "four" ] && continue
set -- "$@" "$dir"
done
rm -rf "$@"
or you get to use find
find ./parent -mindepth 1 -name four -prune -o -exec rm -rf {} \;
or (with find
that has -exec +
to save on some rm
executions)
find ./parent -mindepth 1 -name four -prune -o -exec rm -rf {} +
Oh, or assuming the list of directories isn't too large and unwieldy I suppose you could always use
rm -rf parent/*<ctrl-x>*
then delete the parent/four
entry from the command line and hit enter where <ctrl-x>*
is readline's default binding for glob-expand-word
.
Related Topics
Add Timestamp to Cat Output from Shell Script
Aborting a Blocking Read on Linux
Why Can One Remove/Rename Open Files in Linux
How to Make Libusb Library Visible to Another Program
Better Way to Check Linux Version
Polling a Loop Device Through a Kernel Module
Linux Configuration - Ssmtp: Cannot Open Smtp.Gmail.Com:587
Difference Between Wic and Hddimg Format in Yocto
Difference Between Starting a Command Using Init.D Script and Service Start
Ld_Library_Path: How to Find a Shared Object
Elf File Tls and Load Program Sections
Binding on a Port with Netpipes/Netcat
How to Attach Domain Name to My Server
Installing New Version of Python on Debian Linux Server
Xfs - How to Not Modify Mtime When Writing to File
Analyze Memory with Crash with Kdump