Dec 09 2021 07:31 AM - edited Dec 09 2021 07:34 AM
I am hoping someone can point me to documentation or explain how/why this is working in a script that I've written. What I needed to do is make PowerShell create a report of any duplicated file in a directory. I've done this via hash, and the script works great. I did it by compiling an array of all files, and then checking if the count of a hash is greater than 1, and if it is add that to a second array which is later used to generate a csv report. What I want to have explained to me or to have someone point me to something that will explain it for me is this line:
foreach ($file in $files)
{
$howMany = $files.hash -match $file.hash
if ($howMany.count -gt 1)
{
$copiedDoc += $file
}
}
The line that I have bolded there, why does that work? Does PowerShell just know to make $howMany an array because it's being set equal to an array of matches against the $file, and so when you do the .count it works? The reason I'm confused is I'm looking at $howMany as a variable, not an array because I create blank arrays at the start of the script to fill in later and this isn't one of them, so it shouldn't be able to store more than one value in it... right?
I'm still pretty new to PowerShell scripting, and I apologize if this is a stupid question.
Dec 09 2021 03:25 PM - edited Dec 10 2021 01:08 AM
SolutionHello @Rich89,
Excerpt from -match operator documentation:
...When the input is a collection of values, the operators return any matching members. If there are no matches in a collection, the operators return an empty array.
So in your specific use case:
$howMany = $files.hash -match $file.hash
If there are identical files in $files.hash collection, your $howMany variable will contain collection of matching hashes.(in this case there will be at least 2 members).
If there are no duplicates of specific file hash your $howMany variable will contain empty array.
Reference: about_Comparison_Operators.MatchingOperators
Hope that helps.
Dec 09 2021 03:34 PM
Dec 09 2021 03:25 PM - edited Dec 10 2021 01:08 AM
SolutionHello @Rich89,
Excerpt from -match operator documentation:
...When the input is a collection of values, the operators return any matching members. If there are no matches in a collection, the operators return an empty array.
So in your specific use case:
$howMany = $files.hash -match $file.hash
If there are identical files in $files.hash collection, your $howMany variable will contain collection of matching hashes.(in this case there will be at least 2 members).
If there are no duplicates of specific file hash your $howMany variable will contain empty array.
Reference: about_Comparison_Operators.MatchingOperators
Hope that helps.