The function I wrote here accepts three mandatory parameters: an input file, a list containing at least one hash algorithm(s), and an output file that saves the hash values of that input file. This function attempts to accept three needed parameters: input file, list of at least one hash algorithms, and output file that saves the hashed values of that input file. I am trying to complete the function by writing the code needed to efficiently and effectively implement this function in the specified block. I am attempting to implement some form of looping to access the elements in $hashAlgorithm.
function Return-FileHash {
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[ValidateSet("SHA1","SHA256","SHA384","SHA512","MD5")]
[STRING[]]
# the array list that contains one or more hash algorithm input for Get-FileHash cmdlet
$hashAlgorithm,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$true)]
# the document or executable input/InputStream for Get-FileHash cmdlet
$filepath,
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$true)]
# the output file that contains the hash values of $filepath
$hashOutput
)
#============================ begin ====================
# Here, I am trying to use a loop expression to implement this
for( $i = 0; $i -lt $hashAlgorithm.Length; $i++)
{
Get -FileHash $hashAlgorithm -SHA1 | $hashOutput
}
# === end =================
Return-FileHash
I get this:
At line:19 char:38
+ Get -FileHash $hashAlgorithm -SHA1 | $hashOutput
+ ~~~~~~~~~~~
Expressions are only allowed as the first element of a pipeline.
At line:1 char:26
+ function Return-FileHash {
+ ~
Missing closing '}' in statement block or type definition.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline
To access the individual elements of $hashAlgorithm
in the for
loop, index into it with the current value of $i
:
for ( $i = 0; $i -lt $hashAlgorithm.Length; $i++) {
Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] | ...
}
Alternatively use a foreach()
loop:
foreach($algo in $hashAlgorithm.Length) {
Get-FileHash $filepath -Algorithm $algo | ...
}
To output to a file at path $hashOutput
, either use the file redirection operators:
# `>` means "overwrite"
Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] > $hashOutput
# `>>` means "append"
Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] >> $hashOutput
Or pass $hashOutput
as an argument to a command that writes the output to disk:
Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] | Add-Content -Path $hashOutput