powershellfileinfo

PowerShell: recursively go through a folder, its subfolders and files -> export fileinfo to .csv


I'm trying to build a powershell-script that would recursively go through a specific folder and its subfolders to list all files within.

In addition, I want to calculate both MD5 and SHA1 hashes, together with the filesize in B and export the results to a CSV.

So, per file, I need:

I was able to come up with the following;

gci -Recurse -Exclude *.txt, *.ps1, *.csv | select FullName | %{get-Filehash -Algorithm md5 -Path $_.FullName ; get-FileHash -Algorithm sha1 -Path $_.FullName ; (Get-Item -Path $_.FullName).Length} | export-csv -Path $PSScriptRoot\md5hashes.csv -NoTypeInformation

In Powershell, this looks OK-ish, but in the .csv there's no filesize included.

Many thanks for your time in advance!


Solution

  • You were close, but trying to write all in one extremely long line is bad practice.
    When you indent your code properly, it is much easier to spot mistakes.

    Try

    $result = foreach ($file in (Get-ChildItem -Path $PSScriptRoot -Exclude *.txt, *.ps1, *.csv -File -Recurse)) {
                [PsCustomObject]@{
                    Path = $file.FullName  # append | Resolve-Path -Relative if you want the relative path
                    Size = $file.Length
                    MD5  = ($file | Get-FileHash -Algorithm MD5).Hash
                    SHA1 = ($file | Get-FileHash -Algorithm SHA1).Hash
                }
    }
    $outFile = Join-Path -Path $PSScriptRoot -ChildPath 'filehashes.csv'
    $result | Export-Csv -Path $outFile -NoTypeInformation