PowerShell Get-FileHash 摆脱空行

PowerShell Get-FileHash get rid of empty lines

我有遍历文件的 foreach 循环,获取路径并在获取哈希的命令中替换它:

$hash = @{}
...
defining variables here
...
foreach($line in $lines)
{
    Get-FileHash $line -Algorithm md5 | format-list | Where { $_ } |  Out-File -Width 200 'hash.txt' -Encoding ascii -Append
    Get-FileHash $line -Algorithm sha256 | format-list | Where { $_ } |  Out-File -Width 200 'hash.txt' -Encoding ascii -Append
    Get-FileHash $line -Algorithm sha512 | format-list | Where { $_ } | Out-File -Width 200 'hash.txt' -Encoding ascii -Append
    @('MD5','SHA256','SHA512') | % { Get-FileHash -Algorithm $_ $line } |  export-csv hash.csv -Delimiter "," -Append
}

我面临的问题是文件开头有 2 个空行,文件末尾有 4 个空行,输出如下:



Algorithm : MD5
Hash      : xxx
Path      : xxx

Algorithm : SHA256
Hash      : xxx
Path      : xxx

Algorithm : SHA512
Hash      : xxx
Path      : xxx




我应该如何去除文件开头和结尾的空行?

您可以一步格式化所有输出,然后 trim 在写入文件之前对其进行格式化:

($lines | foreach {
      foreach ($alg in ('MD5','SHA256','SHA512')) {
          Get-FileHash $_ -Algorithm $alg
      }
} | format-list | out-string).trim() | Out-File 'hash.txt' -Encoding ascii