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
Related
Folder X has a lot of subfolders A,B,C,D... each subfolder has a lot of files and I want to archive all files that are in those subfolders and that are older than 6 months. After that check if archive is created and delete the files that have been archived.
Here is what I tried:
#$SourceFolder = "C:\Users\sec\Desktop\X"
ForEach-Object
{
Get-ChildItem -Path "$($_.FullName)" -Exclude "*.zip"
Where-Object {($_.LastWriteTime -lt (Get-Date).AddMonths(-6))} |
Compress-Archive -DestinationPath "$($_.FullName)\06.2020andOlder.zip" -Update;
if (Test-Path 06.2020andOlder.zip) {
Remove-Item -Force
}
}
Assuming you want each subfolder to end up with a .zip archive where the older files are in, try this:
Use Group-Object to group all older files within the same subdirectory together and use that to the create the .zip file and also to remove the original files after zipping.
$SourceFolder = 'D:\Test'
$refDate = (Get-Date).AddMonths(-6).Date # take this from midnight
Get-ChildItem -Path $SourceFolder -File -Recurse -Exclude "*.zip" |
Where-Object { $_.LastWriteTime -lt $refDate } |
Group-Object DirectoryName | ForEach-Object {
# construct the target folder path for the zip file using the Name of each group
$zip = Join-Path -Path $_.Name -ChildPath '06.2020andOlder.zip'
# archive all files in the group
Compress-Archive -Path $_.Group.FullName -DestinationPath $zip -Update
# here is where you can delete the original files after zipping
$_.Group | Remove-Item -WhatIf
}
Note I have added switch -WhatIf to the Remove-Item cmdlet. This is a safety switch, so you are not actually deleting anything yet. The cmdlet now only displays what would be deleted. Once you are happy with this output, remove that -WhatIf switch so the files are deleted.
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
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.
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.
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 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