我需要一个嵌套的 foreach 循环来完成这个吗?

问题描述 投票:0回答:1

看着这段代码,我设法拼凑在一起:

Get-ChildItem -Path "$hashpath" -Recurse -File | 
Select @{N='FileHash'; E={(Get-FileHash -LiteralPath $_.FullName -algorithm MD5).Hash}},FullName,Length,LastWriteTime |
    ForEach-Object {
        $_.FullName=($_.FullName -replace [regex]::Escape("$hashpath"), '')
        $_.LastWriteTime=($_.LastWriteTime).ToSTring('yyyyMMdd_HHmmss')
        Write-Host "$($count) of $($numfiles)" $_.FileHash $_.FullName $_.Length $_.LastWriteTime
        ++$count
        Write-Output "$($_.Filehash) $($_.FullName) $($_.Length) $($_.LastWriteTime)" } | 
    Format-Table -AutoSize -HideTableHeaders | 
    Out-String -Width 4096 | 
    Out-File -Encoding ASCII -FilePath "$hashlog" -Append

如所写,它在计算文件哈希后显示

Write-Host "$($count of $($numfiles)" $_.FileHash $_.FullName $_.Length
。我希望它在计算文件哈希之前显示它。

我尝试在里面嵌套另一个

foreach-object
,但我似乎无法正确传递参数。

非常感谢任何帮助,谢谢。

powershell foreach nested-loops
1个回答
0
投票
$count = 1
$numfiles = (Get-ChildItem -Path $hashpath -Recurse -File).Count

Get-ChildItem -Path $hashpath -Recurse -File | ForEach-Object {
    $fileInfo = $_
    $fullName = $fileInfo.FullName -replace [regex]::Escape($hashpath), ''
    $lastWriteTime = $fileInfo.LastWriteTime.ToString('yyyyMMdd_HHmmss')

    Write-Host "$count of $numfiles $fullName $($fileInfo.Length) $lastWriteTime"
    $count++

    $fileHash = (Get-FileHash -LiteralPath $fileInfo.FullName -Algorithm MD5).Hash
    "$fileHash $fullName $($fileInfo.Length) $lastWriteTime"
} | Format-Table -AutoSize -HideTableHeaders | Out-String -Width 4096 | Out-File -Encoding ASCII -FilePath $hashlog -Append

在此更新中使用

$fileHash
变量来保存计算出的哈希值,然后再将其用于输出。在计算哈希之前,使用
Write-Host
显示信息,然后将准备好的输出提供给管道。

© www.soinside.com 2019 - 2024. All rights reserved.