I want to exclude only certain folders when I delete files in folders in Powershell

Asked 2 years ago, Updated 2 years ago, 409 views

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

powershell

2022-09-30 22:01

2 Answers

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


2022-09-30 22:01

Now that you've organized your questions,

$filePath='C:\temp\"# folder to be deleted
$excludeItem='Processed'# Folder you want to exclude within deletion

Assume

  • $filePathI want to recursively delete my subordinates
  • However, I want to exclude $ excludeItem directly under $filePath from deletion

Is 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.

$filePathrecursively removes subordinates

  • $filePathRecursively delete directories directly below (except $excludeItem)
  • $filePathDelete the file directly below

If 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?


2022-09-30 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.