As you can see in the title, I don't want to delete only certain folders as below.
It's not working.
Is there any way?
$filePath='C:\temp\"# folder to be deleted
$excludeItem='Processed'# Folder you want to exclude within deletion
Get-ChildItem-Path$filePath-Exclude$ExcludeItem-Recurse | Where-Object{$_.LastWriteTime-lt(Get-Date).AddDays(-2)}|Remove-Item-Force-WhatIf
You can use the script below.
ls-Path$filePath-Recurse|?{if($_.PSIsContainer){$_.Name-ne$excludeItem-and(ls$_.FullName-Directory-Filter$excludeItem).Count-eq0}else{$_.FullName-notmatch$excludeIrudeIrude}|-Ruce}
Explanation
As you asked, I cannot -Exclude
in the folder, so I will retrieve all the files recursively for now.
ls-Path$filePath-Recurse
The following Where-Object (alias ?{}
) may simply be used, but the subfolder $ excludeItem
will not be considered.
In other words, even if C:\temp\hoge\processed\
exists, it is not allowed because it tries to delete C:\temp\hoge\
.
ls-Path$filePath-Recurse|?{$_.fullname-notmatch$excludeItem}
To avoid this, we separated the processing of folders and files in Where-Object.
?{
if($_.PSIsContainer){
# For folders, the folder name is not $excludeItem and there is no $excludeItem in the child folder.
$_.Name-ne$ excludeItem-and
(ls$_.FullName-Directory-Filter$excludeItem).Count-eq0
} else {
# For files, do not include $excludeItem in the full path
$_.FullName-notmatch$ excludeItem
}
}
Then delete the appropriate file folder.(Of course - WhatIf
option does not actually disappear)
|rm-Recurse-Force-WhatIf
Now that you've organized your questions,
$filePath='C:\temp\"# folder to be deleted
$excludeItem='Processed'# Folder you want to exclude within deletion
Assume
$filePath
I want to recursively delete my subordinates$ excludeItem
directly under $filePath
from deletionIs that so?
-Exclude
in Get-ChildItem
specifies the name to exclude; for example, *.txt
can be used to exclude individual file names.It doesn't have the ability to exclude everything below a specific directory like this one.
$filePath
recursively removes subordinates
$filePath
Recursively delete directories directly below (except $excludeItem
)$filePath
Delete the file directly belowIf you think about it separately, I think I can write a simple description.Specifically
Get-ChildItem$filePath-Directory-Exclude$ExcludeItem|Remove-Item-Recurse
Get-ChildItem$filePath-File | Remove-Item
So what do you think?
© 2024 OneMinuteCode. All rights reserved.