windowspowershellcommand

PowerShell: Get-ChildItem FullName Output to Get-FileHash Path


New to PowerShell, I'm trying to create a command that does the following:

  • Searches an entire directory for a specific file

  • Uses the file path from Get-ChildItem as a variable for Get-FileHash "-Path"

  • Lists the file's FullName, Attributes, LastWriteTime, CreationTime, LastAccessTime, $Hash ($Hash = output of Get-FileHash)

What I've created so far (that doesn't work):

$ErrorActionPreference = "SilentlyContinue"; $Path = Get-ChildItem -Recurse -Path C:\ -Force -Filter screenshot_37.png | Select-Object FullName; Get-ChildItem -Recurse -Path C:\ -Force -Filter screenshot_37.png |Select-Object FullName, Attributes, LastWriteTime, CreationTime, LastAccessTime, @{Name='Hash';Expression = { $_ |Get-FileHash $Path -Alogorithm MD5 |ForEach-Object Hash }}

Works As Is:

$ErrorActionPreference = "SilentlyContinue"; Get-ChildItem -Recurse -Path C:\ -Force -Filter screenshot_37.png |Select-Object FullName, Attributes, LastWriteTime, CreationTime, LastAccessTime, @{Name='Hash';Expression = { $_ |Get-FileHash -Alogorithm MD5 |ForEach-Object Hash }}

Returns:

FullName : C:\Users\ME\Downloads\Screenshot_37.png

Attributes : Hidden, Archive

LastWriteTime : 10/24/2023 9:32:34 AM

CreationTime : 10/24/2023 9:32:34 AM

LastAccessTime : 10/26/2023 10:37:31 AM

Hash :

Can someone help me in understanding and creating a working command for what's desired?

($ErrorActionPreference = "SilentlyContinue" is present b/c User does not have Admin permissions, therefor searching the C:\ drive produces a lot of errors of access denied)


Solution

  • There's no need to call Get-ChildItem twice - instead, attach the output from Get-FileHash to the original file item:

    Get-ChildItem -Recurse -Path C:\ -Force -Filter screenshot_37.png |Select-Object FullName, Attributes, LastWriteTime, CreationTime, LastAccessTime, @{Name='Hash';Expression = { $_ |Get-FileHash -Algorithm MD5 |ForEach-Object Hash }}
    

    The last argument passed to Select-Object (@{Name='Hash';Expression = { $_ |Get-FileHash -Algorithm MD5 |ForEach-Object Hash }}) is a calculated property table, which allows you to synthesize new properties based on the existing input object.

    You can read more about calculated properties in the about_Calculated_Properties help topic