toma
toma

Reputation: 3

PowerShell Search for specific files - different results each run

I need to search for files of a certain type (photos and videos) in a selected folder and subfolders. Then I have to list them along with the path and size. As a good start, I used the solution provided here but when I execute the script by lit (updated version), it returns each file 4 times (each with a different hash) - in fact, there is only one file on the disk. Also, when I do it again, the hash is different for the same file. What am I doing wrong?

Upvotes: 0

Views: 49

Answers (1)

Theo
Theo

Reputation: 61218

You can use the -Include parameter to have Get-ChildItem return all files with the given set of extensions. This only works if you also specify the -Recurse switch, OR have the path end in \*.

$rootFolder = 'D:\Test'     # change this to the path of your folder
$extensions = '*.jpg', '*.jpeg', '*.png', '*.bmp', '*.mp4', '*.mkv', '*.mts'  # add more extensions if need be

$result = Get-ChildItem -Path $rootFolder -File -Recurse -Include $extensions | ForEach-Object {
    # output an object with properties you need
    [PsCustomObject]@{
        File = $_.FullName
        Hash = (Get-FileHash -Path $_.FullName -Algorithm MD5).Hash  # choose another algorithm if you don't like MD5
    }
}

# output to console
$result | Format-Table -AutoSize

# output to CSV file
$result | Export-Csv -Path (Join-Path -Path $rootFolder -ChildPath 'hashcodes.csv') -UseCulture -NoTypeInformation

P.S. The GetHashCode() method on an object such as a FileInfo object is not a good way to determine a file hash for files. It is one of the simplest ways to compute a hash code for a numeric value that has the same or a smaller range than the Int32 type is to simply return that value. Better use the Get-FileHash cmdlet for that

Upvotes: 0

Related Questions