powershell - Filtering files by partial name match -
i have network share 20.000 xml files in format
username-computername.xml
there duplicate entries in form of (when user received new comptuer)
user1-computer1.xml
user1-computer2.xml
or
blrppr-skb52084.xml
blrsia-skb50871.xml
s028ds-skb51334.xml
s028ds-skb52424.xml
s02fl6-skb51644.xml
s02fl6-skb52197.xml
s02vud-skb52083.xml
since im going manipulate xmls later can't dismiss properties of array @ least need full path. aim is, if duplicate found, 1 newer timestamp being used.
here snipet of code need logic
$xmlfiles = get-childitem "network share"
here i'm doing foreach
loop:
foreach ($xmlfile in $xmlfiles) { [xml]$xmlcontent = get-content -path $xmlfile.fullname -encoding utf8 select-xml -xml $xmlcontent -xpath " " # create [pscustomobject] etc... }
essentially need is
if ($xmlfiles.name.split("-")[0]) - duplicate) { # select 1 higher $xmlfiles.lastwritetime , store either # full object or $xmlfiles.fullname }
ideally should part of foreach
loop not have loop through twice.
you can use group-object
group files custom attribute:
$xmlfiles | group-object { $_.name.split('-')[0] }
the above statement produce result this:
count name group ----- ---- ----- 1 blrppr {blrppr-skb52084.xml} 1 blrsia {blrsia-skb50871.xml} 2 s028ds {s028ds-skb51334.xml, s028ds-skb52424.xml} 2 s02fl6 {s02fl6-skb51644.xml, s02fl6-skb52197.xml} 1 s02vud {s02vud-skb52083.xml}
where group
property contains original fileinfo
objects.
expand groups in foreach-object
loop, sort each group lastwritetime
, , select recent file it:
... | foreach-object { $_.group | sort-object lastwritetime -desc | select-object -first 1 }
Comments
Post a Comment