Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

filter - Using a PowerShell script, is there a way to get a list of Items from a folder that excludes items that have a duplicate BaseName?

I want to store items in a var from a directory with duplicate names, but different extensions. For example: there are files with .jpg and files with .webp with the same BaseName. I would like to excludes those and only add the ones that don't have a similar .webp twin.

Code I used to get all the files:

$images = Get-ChildItem $dir

I would like to store all the files that don't have a .webp twin with the same BaseName in $images.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the Group-Object cmdlet:

$images = Get-ChildItem -File $dir*.jpg, $dir*.webp |
            Group-Object BaseName |
              Where-Object { $_.Group.Extension -notcontains '.webp' } |
                ForEach-Object Group

Note: If recursive file retrieval were to be used (-Recurse), you could simplify to
Get-ChildItem -Recurse -File $dir -Include *.jpg, *.webp; perhaps surprisingly, -Include is only properly supported with -Recurse - see GitHub issue #3304.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...