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

Categories

0 votes
373 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...