Trying just to write a simple script that would return the SHA256 signature of a file using the file name passed to my ps1 script :
The scriptname is sha256sum.ps1
.
The first argument will be any file, example :
sha256sum.ps1 dummy.exe
I tried these inside sha256sum.ps1
:
Get-FileHash -algo SHA256 %1
Get-FileHash -algo SHA256 $1
Get-FileHash -algo SHA256 $args[1]
but none of them worked.
Is there a simple way to do that ?
EDIT : Here is the final version of my script thanks to your help, guys :)
param($filename)
function calcSignature() {
$scriptName = Split-Path -Leaf $PSCommandPath
switch( $scriptName ) {
"md5sum.ps1" { $algo = "MD5"; Break }
"sha1sum.ps1" { $algo = "SHA1"; Break }
"sha256sum.ps1" { $algo = "SHA256"; Break }
"sha384sum.ps1" { $algo = "SHA384"; Break }
"sha512sum.ps1" { $algo = "SHA512"; Break }
}
(Get-FileHash -algo $algo $filename).Hash " " $filename
}
calcSignature
Now I only have one script and the others are links pointing to sha256sum.ps1
.
CodePudding user response:
I'm guessing you're looking for "How to pass an argument to your .ps1
script".
This is an example of how the script sha256sum.ps1
would look:
param(
[parameter(mandatory)]
[validatescript({
Test-Path $_ -PathType Leaf
})]
[system.io.fileinfo]$File
)
(Get-FileHash $File -Algorithm SHA256).Hash
Now, if we were to call this script, as an example:
PS \> .\sha256sum.ps1 .\test.html
1B24ED8C7929739D296DE3C5D6695CA40D8324FBF2F0E981CF03A8A6ED778C9C
Note: the current directory is where the script and the html file are located, if that was not the case, you should use the absolute path.
I would recommend you to the official docs to get a concept on functions and the param(...)
block.
CodePudding user response:
Santiago's helpful answer shows how you to properly declare parameters for your script, which is generally preferable.
As for what you tried:
The automatic $args
variable contains arguments not bound to any declared parameters. In other words: if your script doesn't declare any parameters, $args
is the only way to access any arguments that were passed.
The first argument is at index 0
, not 1
.
Note:
- This differs from other shells / programming language where the element at index
0
reflects the script / program being called.- To get the full path of the enclosing script in PowerShell, use the automatic
$PSCommandPath
variable.
- To get the full path of the enclosing script in PowerShell, use the automatic
- Thus, for instance,
%1
in a batch file and$1
in abash
script - both of which contain the first argument - correspond to$args[0]
in PowerShell.
Therefore, Get-FileHash -algo SHA256 $args[0]
should have worked.