'Powershell save the results GetFileHash within If and else

So I am using PowerShell script : If the path exist then Get me the hash value :

$Path = 'c:\exampel\example.text'
if (Test-Path $Path){
Get-FileHash $Path | Format-List
else {
write-Host "File Not found!"}

The result is :

Algorithm : SHA256 Hash : 6A785ADC0263238DAB3EB37F4C185C8FBA7FEB5D425D034CA9864F1BE1C192kd Path : c:\exampel\example.text

I tried but the file was not found and there is no result.

if (Test-Path $Path){
Get-FileHash $Path | Format-List | export-csv c:\example.csv

My question is how can I save the result to a file.txt?



Solution 1:[1]

As Lee_Dailey commented, never use Format-* cmdlets if you want to process the data any further (like saving it in a CSV in this case).

Format-* cmdlets are for display purposes ONLY and will mess up your original data.

Try

$Path = 'c:\exampel\example.text'
if (Test-Path -Path $Path -PathType Leaf) {
    Get-FileHash -Path $Path | Export-Csv -Path 'c:\example.csv' -NoTypeInformation
}
else { Write-Host "File Not found!"}

The resulting CSV file, when opened in notepad should then look like

"Algorithm","Hash","Path"
"SHA256","6A785ADC0263238DAB3EB37F4C185C8FBA7FEB5D425D034CA9864F1BE1C192kd","C:\exampel\example.text"

if you need to do this on a series of file paths you read from a text file, do:

# change the path to your text file
$allFiles = Get-Content -Path 'X:\somewhere\filepaths.txt'
# loop over the paths
$result = foreach ($Path in $allFiles) {
    if (Test-Path -Path $Path -PathType Leaf) {
        # output the object so it gets collected in variable $result
        Get-FileHash -Path $Path
    }
    else { 
        Write-Host "File '$Path' Not found"
    }
}
# now save the results in your csv
$result | Export-Csv -Path 'c:\example.csv' -NoTypeInformation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1