1

我在这里编写的函数接受三个强制参数:一个输入文件、一个包含至少一个哈希算法的列表和一个保存该输入文件哈希值的输出文件。此函数尝试接受三个需要的参数:输入文件、至少一个哈希算法的列表以及保存该输入文件的哈希值的输出文件。我正在尝试通过编写在指定块中高效且有效地实现此功能所需的代码来完成该功能。我正在尝试实现某种形式的循环来访问 $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

我明白了:

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
4

1 回答 1

1

$hashAlgorithm要访问循环中的各个元素,请for使用 的当前值对其进行索引$i

for ( $i = 0; $i -lt $hashAlgorithm.Length; $i++) {
    Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] | ...
}

或者使用foreach()循环:

foreach($algo in $hashAlgorithm.Length) {
    Get-FileHash $filepath -Algorithm $algo | ...
}

要输出到 path 处的文件$hashOutput,请使用文件重定向运算符:

# `>` means "overwrite"
Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] > $hashOutput
# `>>` means "append"
Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] >> $hashOutput

或者$hashOutput作为参数传递给将输出写入磁盘的命令:

Get-FileHash $filepath -Algorithm $hashAlgorithm[$i] | Add-Content -Path $hashOutput
于 2020-04-28T16:28:55.423 回答