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?
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.
In PowerShell 3.0 and below, you can try simply doing this:
Remove-Item -recurse c:\temp\* -exclude somefile.txt,foldertokeep
Unless there's some parameter I'm missing, this seems to be doing the trick...
Edit: see comments below, the behavior of Remove-Item has changed after PS3, this solution doesn't seem applicable anymore.
Select everything excluding what needs to be keep and pipe that to a delete command.
Say you have those folders
C:.
├───delme1
│ │ delme.txt
│ │
│ └───delmetoo
├───delme2
├───keepme1
│ keepmetoo.txt
│
└───keepme2
To delete everything but preserve the keepme1 and keepme2 folders.
Get-ChildItem -Exclude keepme1,keepme2 | Remove-Item -Recurse -Force
Other solutions are fine but I found this easy to understand and to remember.
I used the below and just removed -Recurse from the 1st line and it leaves all file and sub folders under the exclude folder list.
Get-ChildItem -Path "PATH_GOES_HERE" -Exclude "Folder1", "Folder2", "READ ME.txt" | foreach ($_) {
"CLEANING :" + $_.fullname
Remove-Item $_.fullname -Force -Recurse
"CLEANED... :" + $_.fullname
}
Yes I know this is an old thread. I couldn't get any of the answers above to work in Powershell 5, so here is what I figured out:
Get-ChildItem -Path $dir -Exclude 'name_to_ignore' |
ForEach-Object {Remove-Item $_ -Recurse }
This moves the -Recurse to Remove-Item instead of where the items are found.
According to MSDN Remove-Item has a known issue with the -exclude param. Use this variant instead.
Get-ChildItem * -exclude folderToExclude | Remove-Item
I ran into this and found a one line command that works for me. It will delete all the folders and files on the directory in question, while retaining anything on the "excluded" list. It also is silent so it won't return an error if some files are read-only or in-use.
#powershell Remove-item C:\Random\Directory\* -exclude "MySpecialFolder", "MySecondSpecialFolder" -force -erroraction 'silentlycontinue'
This would also help someone...
Adding a variable for PATH_GOES_HERE that is empty or isn't defined prior can cause a recursive deletion in the user directory (or C:\windows\system32 if the script is ran as admin). I found this out the hard way and had to re-install windows.
Try it yourself! (below will only output the file directories into a test.txt)
Get-ChildItem -Path $dir2 -Recurse -Exclude "Folder1 ", FileName.txt | foreach ($_) {
$_.fullname >> C:\temp\test.txt
}
I used this, that works perfectly for me
Get-ChildItem -Path 'C:\Temp\*' -Recurse | Where-Object {($_.FullName -notlike "*windirstat*") -and ($_.FullName -notlike "C:\Temp\GetFolderSizePortable*")} | Remove-Item -Recurse
If your paths include regex special characters then you need to use the -LiteralPath option which does not allow piping. The correct solution in that case looks like this:
Remove-Item -force -LiteralPath(
Get-ChildItem -Path 'C:\temp' -Recurse -exclude somefile.txt |
Select-Object -ExpandProperty FullName |
Where-Object { $_ -notlike 'C:\temp\foldertokeep*' } |
Sort-Object length -Descending
)
This would also help someone...
Get-ChildItem -Path PATH_GOES_HERE -Recurse -Exclude "Folder1 ", "Folder2", FileName.txt | foreach ($_) {
"CLEANING :" + $_.fullname
Remove-Item $_.fullname -Force -Recurse
"CLEANED... :" + $_.fullname
}
I want get contribution for this idea
delete all folder and files include hidden folder
$get-childitem -Path D:\path\folder\to\delete* -Force |select-object -Expandproperty Fullname |remove-item -recurse -Confirm:$false -Force
delete all folder and file include hidden folder but retain exclude folder
$get-childitem -Path D:\path\folder\to\delete* -Exclude nameexludefolder -Force | select-object -Expandproperty Fullname | remove-item -Force
$get-childitem -Path D:\path\folder\to\delete\ -Exclude nameexludefolder -Force | select-object -Expandproperty Fullname | remove-item -Force
first line remain folders,
2nd line remove remain folder
Related
I need to delete some subfolders under a folder 'ToDelete'. I am using this to do that: (both should do the same deletion). my problem is that there is other folder called 'Do_Not_Copy' under ToDelete folder that contain also a folder called 'Tools' that should not be deleted. how I can protect this 'Tools' subfolder? -Exclude doesn't work.
My workaround for now is to use Rename-Item for the Tools folder
$DestinationFolder = "\\google\server\ToDelete"
Remove-Item -Path $DestinationFolder\ -Include "Tools", "Support", "Installer", "GUI", "Filer", "Documentation" -Recurse -Exclude "Do_not_copy\SI\Tools" -Force
Get-ChildItem $DestinationFolder\ -Include "Tools", "Support", "Installer", "GUI", "Filer", "Documentation" -Recurse -Force | ForEach-Object { Remove-Item -Path $_.FullName -Recurse -Force }
The -Recurse switch does not work properly on Remove-Item (it will try to delete folders before all the subfolders in the folder have been deleted).
Sorting the fullnames in descending order by length ensures than no folder is deleted before all the child items in the folder have been deleted.
Try
$rootFolder = '\\google\server\ToDelete'
# create a regex of the folders to exclude
$Exclude = 'Do_not_copy\SI\Tools' # this can be an array of items to exclude or a single item
# each item will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($Exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'
# the array of folder names (not full paths) to delete
$justThese = 'Tools', 'Support', 'Installer', 'GUI', 'Filer', 'Documentation'
(Get-ChildItem -Path $rootFolder -Directory -Recurse -Include $justThese).FullName |
Where-Object { $_ -notmatch $notThese } |
Sort-Object Length -Descending |
Remove-Item -Recurse -Confirm:$false -Force -WhatIf
As usual, I have added the -WhatIf safety switch, so no folders will be deleted and in the console you can see what would happen.
When satisfied the correct folders will be removed, comment out or remove that -WhatIf switch and run again
I am trying to write a script in Powershell to remove some files automatically with a certain file name.
My idea is to get all the folders in the directory, then loop through the subdirectory, and remove all items with the file name, but it doesn't seem to be working as expected.
Here is my script
$folders = Get-ChildItem -path "C:\Website-Backup" -Recurse | Where-Object {$_.PsIsContainer} |Group-Object {$_.FullName.Split('_')[0] }
$subfolders = Get-ChildItem -path $folders -Recurse | Where-Object {$_.PsIsContainer} | Group-Object {$_.FullName.Split('_')[0] }
ForEach($subfolder in $subfolders)
{
Remove-Item * -Include *100x*
}
Any idea why the script doesn't seem to be doing anything?
I think you can simplify your code if I understand correctly to:
Get-ChildItem "C:\Website-Backup" -Recurse -include "*100x*" -file | remove-item
The Group-Object command is likely what's confusing things here - Remove-Item is expecting a path - you're not referencing the subfolder variable in your loop as well, so this is the same as just running the Remove-Item command as many times as there are items in the array.
You can try this instead;
Get-ChildItem -Path "C:\Website-Backup" -Recurse | Where-Object -FilterScript { $_.name -like 'MyFile.txt' } | Remove-Item
This will pipe the returned child items into Where-Object, filter it to the specified file name, then pass that to Remove-Item as a file path.
You can also skip the Where-Object, but you lose a bit of control this way;
Get-ChildItem -Path 'C:\WebSiteBackup\*MyFile.txt' -Recurse | Remove-Item
Delete all Files in C:\temp older than Current day(s)
$Path = "E:\Testing\Order\123456"
$CurrentDate = Get-Date
Get-ChildItem $Path | Where-Object { $_.LastWriteTime -lt $CurrentDate } | Remove-Item
I am trying to run this script but it is deleting every thing. It is not maintain current date files. Is there any modification please suggesting me sir.
Make sure you get the file extensions right if they have any.
Get-ChildItem -Path C:\folder1\data -Include * -Exclude text.1, folder1 -Recurse | foreach { $_.Delete()}
Edit to answer the comment:
So you want to delete all files and folders in C:\folder1 except of files text.1 and folder.1 in data, other and alpha? It means you cannot remove these 3 folders too so they have to be excluded.
Get-ChildItem -Path C:\folder1\ -Include * -Exclude text.1, folder.1, alpha, data, other -Recurse | foreach { $_.FullName}
try this (and dont stay into your dir when you try) :
Get-ChildItem "C:\folder1\data\*" -Recurse | where Name -notin ('text.1', 'folder.1') | Remove-Item -Force -Recurse
How can I find Folders called BlueMountain when this folder could be nested anywhere in my Users home folder
\\Server\Users\<personsname>\
Ultimately I want to delete the folder but just to be on the safe side. The BlueMountain folder must have one of these subfolder
Certs
Config
Macros
Scripts
Spool
Traces
Transfer
This is what I have so far
Get-ChildItem -Path \\Server\Users -Recurse -Directory -Filter $_.FOLDERNAME | ForEach-Object {
If $_.FullName --eq "BlueMountain" {
}
}
You can use -recurse to look for the last thing in your path recursively. So this:
Get-ChildItem \\server\Users\BlueMountain -recurse
Will look in all subfolders of "\server\Users" for anything named "BlueMountain". Then you just need to make sure it has one of your folders.
$SubFolders = 'Certs','Config','Macros','Scripts','Spool','Traces','Transfer'
Get-ChildItem \\server\Users\BlueMountain -recurse | Where{Get-ChildItem "$($_.FullName)\*" -Include $SubFolders}
That should list only the BlueMountain folders found recursively in \server\Users which contain one of the specified subfolders. Then you can just pipe that to Remove-Item -force and call it a day. Or if you want to track things pipe it to tee-object and then to remove-item.
try this :
$SubFolders = 'Certs','Config','Macros','Scripts','Spool','Traces','Transfer'
$wordtosearch="BlueMountain"
$SearchPattern= ($SubFolders | %{ "$wordtosearch\\$_" }) -join "|"
get-childitem "\\Server\Users" -directory -Recurse |
where FullName -match $SearchPattern |
Split-Path -path {$_.FullName} -Parent |
remove-item -Recurse -ErrorAction SilentlyContinue
I am attempting to delete all directories, sub-directories, and the files contained in them based on a filter that specifies the required directory/sub-directory name.
For example, if I have c:\Test\A\B.doc, c:\Test\B\A\C.doc, and c:\Test\B\A.doc and my filter specifies all directories named 'A', I would expect the remaining folders and files to be c:\Test, c:\Test\B and c:\Test\B\A.doc respectively.
I am trying to do this in PowerShell and am not familiar with it.
The following 2 examples will delete all of the files that match my specified filter, but the files that match the filter as well.
$source = "C:\Powershell_Test" #location of directory to search
$strings = #("A")
cd ($source);
Get-ChildItem -Include ($strings) -Recurse -Force | Remove-Item -Force –Recurse
and
Remove-Item -Path C:\Powershell_Test -Filter A
I would use something like this:
$source = 'C:\root\folder'
$names = #('A')
Get-ChildItem $source -Recurse -Force |
Where-Object { $_.PSIsContainer -and $names -contains $_.Name } |
Sort-Object FullName -Descending |
Remove-Item -Recurse -Force
The Where-Object clause restricts the output from Get-ChildItem to just folders whose names are present in the array $names. Sorting the remaining items by their full name in descending order ensures that child folders get deleted before their parent. That way you avoid errors from attempting to delete a folder that had already been deleted by a prior recursive delete operation.
If you have PowerShell v3 or newer you can do all filtering directly with Get-ChildItem:
Get-ChildItem $source -Directory -Include $names -Recurse -Force |
Sort-Object FullName -Descending |
Remove-Item -Recurse -Force
I don't think you can do it quite that simply. This gets the list of directories, and breaks the path into its constituent parts, and verifies whether the filter matches one of those parts. If so, it removes the whole path.
It adds a little caution to handle if it already deleted a directory because of nesting (the test-path) and the -Confirm helps ensure that if there's a bug here you have a chance to verify the behavior.
$source = "C:\Powershell_Test" #location of directory to search
$filter = "A"
Get-Childitem -Directory -Recurse $source |
Where-Object { $_.FullName.Split([IO.Path]::DirectorySeparatorChar).Contains($filter) } |
ForEach-Object { $_.FullName; if (Test-Path $_) { Remove-Item $_ -Recurse -Force -Confirm } }