Deleting folders with Powershell recursively issue - powershell

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

Related

Powershell move items in subdirectories only for a folder name that contains a certain string

So lets say there are a bunch of folders containing different sub folders. The example below has a root folder of user 1 and 3 sub-directories under that folder. How can I create a looping script to move items from only sub-directories that contain the string "upload" up one level to the user folder.
->user1
--->user1upload
--->randomfolder1
--->randomfolder2
->user2
--->user2upload
--->randomfolder1
--->randomfolder2
So far I have the following code which moves all files in the sub-directories to the root user folder.
$files = Get-ChildItem '*\*\*'
Get-ChildItem $files | Move-Item -Destination { $_.Directory.Parent.FullName }
$files | Remove-Item -Recurse
I want to eliminate the other folders from this so that only folders with 'upload' in its name have the file contents moved up to the root user folder. How can I do this?
EDIT:
also tried this with no luck
$files = Get-ChildItem '*\*\*' | Select-String -Pattern "upload"
Get-ChildItem $files | Move-Item -Destination { $_.Directory.Parent.FullName }
EDIT2 (3/21/2019)
To be clear, his is for an SFTP program. There is a list of user folders in C:/usrs and I want to move files from c:/usrs/user1/user1upload to C:/usrs/user1
This uses PowerShell 5 to specify -Directory. It can be done in a different way if you are not yet to PowerShell 5.
Search for the directories, then search for files within the directories.
When you are confident the the files will be moved correctly, remove the -WhatIf from the Move-Item cmdlet.
Get-ChildItem -Directory -Path $Env:USERPROFILE -Filter '*upload*' |
ForEach-Object {
Get-ChildItem -File -Path $_.FullName |
ForEach-Object {
Move-Item -Path $_.FullName -Destination $_.PSParentPath -WhatIf
}
}
I thought you were in "user's" directories where you typically would not have permission to access all. One more level of directory search.
Get-ChildItem -Directory -Path 'C:\Users\*\*upload*' |
ForEach-Object {
Get-ChildItem -File -Path $_.FullName |
ForEach-Object {
Move-Item -Path $_.FullName -Destination $(Split-Path -Parent $_.PSParentPath) -WhatIf
}
}

Powershell copy directories and contents where name match with filter

I'm trying to use powershell to copy some directories where name match with filter.
First of all I delete all the directories that match in the destination path, alfter I try to copy source directories and contents but I've a problem because are copied only files inside directories and subdirectories and not the directories names and structures.
$source="F:\origin"
$destination="F:\dest"
$filter="#"
# Remove dirs #
Get-ChildItem -Path $destination -Recurse |
Where-Object { $_.DirectoryName -match $filter } |
remove-item -Recurse
# Copy dirs and all contents
Get-ChildItem -Path $source -Recurse |
Where-Object { $_.DirectoryName -match $filter } |
Copy-Item -Destination $destination
How can I do This ?
Thank you
EDIT
F:\origin\#test\index.php
F:\origin\#test1\index1.php
F:\origin\#test1\sub1\subindex1.php
F:\origin\no_consider\index1.php
Expected output
F:\dest\#test\index.php
F:\dest\#test1\index1.php
F:\dest\#test1\sub1\subindex1.php
a couple small tweaks seems to have done the trick. replaced some double quotes with single quotes, added a Recurse at the end of the one line and change DirectoryName to Name for the first one.
LEt me know if this works:
$source='c:\origin'
$destination='c:\dest'
$filter="#"
# Remove dirs #
Get-ChildItem -Path $destination -Recurse |
Where-Object { $_.Name -match $filter } |
remove-item -Recurse
# Copy dirs and all contents
Get-ChildItem -Path $source |
Where-Object { $_.Name -match $filter } |
Copy-Item -Destination $destination -Recurse -Force

I need to find a Folder on the Network Share

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

Recursively Delete Files and Directories Using a Filter on the Directory Name

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 } }

Delete all files and folders but exclude a subfolder

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