powershellcertutil

Saving to file of same name as given path with different extension


What I wanna do: design a command for the Windows Powershell that lets a user input a path to a file they want to have the checksum of as well as their preferred checksum algorithm. The result should then be saved in a file of the same name as that file, in the same directory, but with the checksum algorithm as its extension.

Example: C:\path\to\file.pdf is written into the command and the user will find C:\path\to\file.sha256 that contains the SHA-256 checksum as text.

What I have so far:

Set-Variable -Name "pfad" -Value "C:\path\to\file.pdf"; Set-Variable -Name "algorithmus" -Value SHA256; certutil -hashfile $pfad $algorithmus > $pfad + "." + $algorithmus

If this worked, it would return a file.pdf.SHA256 which would be fine. However, it overwrites the original file with a file of the same name containing an error message.

Unfortunately, some kind of bash script is not viable for me. It has to be one command that the users will be able to copy with their desired values into one place of the command.

I have looked into several functions like SplitPath etc but I feel like there should be a fairly simple way of doing what I want. This is my first time dealing with the Windows Powershell so I'm very ignorant of my possibilities.


Solution

  • I think this will do what you want.
    Instead of setting the variables you can just declare them and set them equal to Read-Host which will get the user input.

    Then you can just pipe the data into a format list and then into a csv file named what you wanted.

    $filePath = Read-Host "Please enter your filepath (e.g. C:\path\to\documents)"
    $fileName = Read-Host "Please enter your filename (e.g. file.pdf)"
    $algorithmus = Read-Host "Please enter your Algorithm format (e.g. SHA256, SHA1, MD5)"
    
    Get-FileHash -Path "$filePath\$fileName" -Algorithm "$algorithmus" | Export-csv "$filePath\$fileName.$algorithmus" -NoTypeInformation
    

    Get-FileHash Docs

    Edit: This will create the file.pdf.sha256 in the same directory as the original file.