powershell - Alternative to "-Contains" that compares value instead of reference -
i have list of file objects, , want check whether given file object appears inside list. -contains
operator i'm looking for, appears -contains
uses strict equality test object references have identical. there less strict alternative? want $boolean
variable in code below return true
second time first time.
ps c:\users\public\documents\temp> ls directory: c:\users\public\documents\temp mode lastwritetime length name ---- ------------- ------ ---- -a---- 14.08.2017 18.33 5 file1.txt -a---- 14.08.2017 18.33 5 file2.txt ps c:\users\public\documents\temp> $files1 = get-childitem . ps c:\users\public\documents\temp> $files2 = get-childitem . ps c:\users\public\documents\temp> $file = $files1[1] ps c:\users\public\documents\temp> $boolean = $files1 -contains $file ps c:\users\public\documents\temp> $boolean true ps c:\users\public\documents\temp> $boolean = $files2 -contains $file ps c:\users\public\documents\temp> $boolean false ps c:\users\public\documents\temp>
get-childitem
returns objects of type [system.io.fileinfo]
.
get-childitem c:\temp\test\2.txt | get-member | select-object typename -unique typename -------- system.io.fileinfo
as petseral mentioned in comments [system.io.fileinfo]
not implement icomparable or iequatable.
[system.io.fileinfo].getinterfaces() ispublic isserial name basetype -------- -------- ---- -------- true false iserializable
without these, noticed powershell support reference equality. lee holmes' has great blog post on this.
the solution make comparisons on sub-properties comparable. can choose specific property unique, fullname
mathias r jessen mentioned. drawback if other properties different, not evaluated.
'a' | out-file .\file1.txt $files = get-childitem . 'b' | out-file .\file1.txt $file = get-childitem .\file1.txt $files.fullname -contains $file.fullname true
alternatively, use compare-object
cmdlet compare of properties between 2 objects (or specific properties choose -property
).
using -includeequal -excludedifferent
flags of compare-object
, can find objects matching properties. when array cast [bool]
, if non-empty $true
, if empty $false
.
'a' | out-file .\file1.txt $files = get-childitem . $file = get-childitem .\file1.txt [bool](compare-object $files $file -includeequal -excludedifferent) true 'a' | out-file .\file1.txt $files = get-childitem . 'b' | out-file .\file1.txt $file = get-childitem .\file1.txt [bool](compare-object $files $file -includeequal -excludedifferent) false
compare-object
can resource intensive, it's best use other forms of comparison when possible.
Comments
Post a Comment