1

I've been using a very simple Get-ChildItem -Recurse command to generate a CSV inventory of a file directory for appraising said files for retention/deletion. I'm very new to PowerShell and I'm trying to keep the code as simple as possible, here is what I've been successfully using:

Get-ChildItem -Recurse | Select-Object FullName, Name, Extension, Length, CreationTime, LastAccessTime, LastWriteTime | Export-Csv "C:\file\path\file_list.csv"

But I would like to add a checksum to the Select-Object, I tried the following code but it created a CSV with only the checksum and no other file data. The checksum should be a column in the CSV next to the other Select-Object parameters.

Get-ChildItem -Recurse | Get-FileHash -Algorithm MD5 | Select-Object FullName, Name, Extension, Length, CreationTime, LastAccessTime, LastWriteTime, Hash | Export-Csv "C:\file\path\file_list.csv"

Any help is greatly appreciated, I'm VERY new to PowerShell, thanks!

  • 1
    Doug's answer works well; in case you're curious about the underlying feature: he used a [calculated property](https://stackoverflow.com/a/39861920/45375), which is a hashtable-based way (`@{ ... }`) to define properties dynamically. – mklement0 Oct 13 '20 at 17:30

1 Answers1

1

Since you want to add it as an additional property, you can use a calculated property like this.

Get-ChildItem -Recurse |
    Select-Object FullName, Name, Extension, Length, CreationTime, LastAccessTime, LastWriteTime, @{n="Hash";e={(Get-FileHash $_.FullName -Algorithm MD5).hash}} |
        Export-Csv "C:\file\path\file_list.csv"

To make it easier to read and maintain, you could use a variable to hold the desired properties like this.

$props = "FullName",
         "Name",
         "Extension",
         "Length",
         "CreationTime",
         "LastAccessTime",
         "LastWriteTime",
         @{n="Hash";e={(Get-FileHash $_.FullName -Algorithm MD5).hash}}

Get-ChildItem -Recurse | Select-Object $props | Export-Csv "C:\file\path\file_list.csv"
Doug Maurer
  • 8,090
  • 3
  • 12
  • 13
  • Thank you Doug! I modified your code a little because some of the files weren't generating a hash, this forces a hash for every file: `Get-ChildItem -Recurse -Force | Select-Object FullName, Name, Extension, Length, LastWriteTime, CreationTime, LastAccessTime, @{n='Hash SHA256';e={(Get-FileHash $_.FullName -Algorithm SHA256).hash}} | Export-Csv “C:\file\path\filelist.csv”` – uraniumcores Oct 13 '20 at 19:11
  • Did you change it to `$_.fullname`? I can edit the post for future readers if you want to tell me what to change. – Doug Maurer Oct 13 '20 at 19:13
  • 1
    Yes, also `-Force` parameter which I think reveals hidden files – uraniumcores Oct 13 '20 at 19:22