Как использовать write-progress в get-filehash - PullRequest
0 голосов
/ 19 ноября 2018

Я хочу получить прогресс при выполнении команды Get-Filehash. Вот код, который у меня есть, но он очень медленный и требует больше времени для выполнения

Set-ExecutionPolicy Unrestricted -force
# Getting Filehash
Write-Host " "
Write-Host "----------------------------------------------------------------------"
Write-Host "Before Proceed, Copy the full Directory path or file path  " -ForegroundColor White -BackgroundColor DarkMagenta
Write-Host "----------------------------------------------------------------------"
Write-Host " "
cd\
cd .\setup
$a=hostname
$output=$a+'hash.txt'
$file = Get-ChildItem -file (Read-Host "Enter Full Directory or File path") -Recurse 
                $filecount= $file.count
                Foreach ($filecount in $file)
                    {
                        $i++
                        Write-Progress -activity "Processing file:- $filecount" -Status "MD5 CheckSum Progress file:- $i" -percentcomplete ($i/$file.count*100)
                        $file | Get-FileHash -Algorithm MD5 |Sort-Object path | Format-Table hash, Path -HideTableHeaders | Out-File $output                    
                    }
if (Test-Path $output) { 
 if((Get-Item $output).length -gt 0kb){
get-Content $output
Write-Host " "
Write-Host "CheckSum Completed Successfully " -ForegroundColor White -BackgroundColor Darkgreen
Write-Host 'Press any key to return to main menu...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
} else {
Write-Host " "
Write-Host "Error Occured" -ForegroundColor red 
Write-Host " "
Write-Host "please check the file name or directory path "
Write-Host " "
Write-Host 'Press any key to return to main menu...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}
}

этот код работает, но очень медленныйобработка.помогите, пожалуйста, сделать скрипт быстрее с прогрессом записи.

второй метод: -

$file = Get-ChildItem -file (Read-Host "Enter Full Directory or File path") -Recurse 
$filecount= $file.count
                For($i = 0; $i -le $filecount; $i++) {
                        Write-Progress -activity "MD5 Check Processing " -Status "Progress file:- $i of $filecount" -percentcomplete ($i/$file.count*100)
                        $file | Get-FileHash -Algorithm MD5 | Sort-Object path | Format-Table hash, Path -HideTableHeaders -AutoSize | Out-File $output -Width 200                                         
                    }

Ответы [ 3 ]

0 голосов
/ 19 ноября 2018

Я только что добавил прогресс записи в существующий скрипт, посмотрите

$Counter = 0
    $Results = foreach ($FL_Item in $FileList)
        {
        $Counter ++
        Write-Progress -Activity "MD5 Check Processing :- $FL_Item " -Status "Processed $Counter " -PercentComplete (($Counter / $FileList.Count) * 100)
        # this will _silently_ skip files that are locked for whatever reason
        $FileHash = Get-FileHash -LiteralPath $FL_Item.FullName -Algorithm MD5 -ErrorAction SilentlyContinue

        # if this is empty, then the "else" block will show "__Error__" in the Hash column
        if ($FileHash)
            {
            [PSCustomObject]@{
                Hash = $FileHash.Hash
                Path = $FileHash.Path
                }
            }
            else
            {
            [PSCustomObject]@{
                Hash = '__Error__'
                Path = $FL_Item.FullName
                }
            } # end >> if ($FileHash)
        } # end >> foreach ($FL_Item in $FileList)
    # send to text file
0 голосов
/ 19 ноября 2018

Я публикую полный скрипт, который хорошо работает с write-progress

Set-ExecutionPolicy Unrestricted -force
# Getting Filehash
Write-Host " "
Write-Host "----------------------------------------------------------------------"
Write-Host "Before Proceed, Copy the full Directory path or file path  " -ForegroundColor White -BackgroundColor DarkMagenta
Write-Host "----------------------------------------------------------------------"
Write-Host " "
cd\
cd .\script
$a=hostname
$output=$a+'hash.txt'
$TargetDir = Read-Host 'Please enter the full path to the target Directory '
$FileList = Get-ChildItem -LiteralPath $TargetDir -Recurse -File 
$filecount= $FileList.count
$Counter = 0
$Results = foreach ($FL_Item in $FileList)
    {
    $Counter ++
    Write-Progress -Activity "MD5 Check Processing :- $FL_Item " -Status "Processed $Counter of $filecount" -PercentComplete (($Counter / $FileList.Count) * 100)
    # this will _silently_ skip files that are locked for whatever reason
    $FileHash = Get-FileHash -LiteralPath $FL_Item.FullName -Algorithm MD5 -ErrorAction SilentlyContinue

    # if this is empty, then the "else" block will show "__Error__" in the Hash column
    if ($FileHash)
        {
        [PSCustomObject]@{
            Hash = $FileHash.Hash
            Path = $FileHash.Path
            }
        }
        else
        {
        [PSCustomObject]@{
            Hash = '__Error__'
            Path = $FL_Item.FullName
            }
        } # end >> if ($FileHash)
    } # end >> foreach ($FL_Item in $FileList)
# send to text file    
$Results |
   Format-Table -HideTableHeaders -AutoSize | Out-File -FilePath $output -Width 200 
0 голосов
/ 19 ноября 2018

ваш код выполняет командлет Get-FileHash для всего набора файлов один раз для каждого файла . [ ухмылка ] обе ваши версии for и foreach имеют всю коллекцию файлов, переданную в командлет для каждого цикла .

вот несколько более чистый способ сделать файлы только один раз каждый ...

# save the old Information preference
$OldInfoPref = $InformationPreference
# enable Information display
$InformationPreference = 'Continue'


$TargetDir = Read-Host 'Please enter the full path to the target Directory '

$FileList = Get-ChildItem -LiteralPath $TargetDir -Recurse -File

$Counter = 0
$Results = foreach ($FL_Item in $FileList)
    {
    $Counter ++
    Write-Information ('Processing file {0} of {1} ...' -f $Counter, $FileList.Count)

    # this will _silently_ skip files that are locked for whatever reason
    $FileHash = Get-FileHash -LiteralPath $FL_Item.FullName -Algorithm MD5 -ErrorAction SilentlyContinue

    # if this is empty, then the "else" block will show "__Error__" in the Hash column
    if ($FileHash)
        {
        [PSCustomObject]@{
            Hash = $FileHash.Hash
            Path = $FileHash.Path
            }
        }
        else
        {
        [PSCustomObject]@{
            Hash = '__Error__'
            Path = $FL_Item.FullName
            }
        } # end >> if ($FileHash)
    } # end >> foreach ($FL_Item in $FileList)

# on screen display
$Results

# send to CSV file    
$Results |
    Export-Csv -LiteralPath "$env:TEMP\FileHashListing.csv" -NoTypeInformation

# restore Information preference
$InformationPreference = $OldInfoPref

частичная активность на экране ...

Please enter the full path to the target Directory : c:\temp
Processing file 1 of 566 ...
Processing file 2 of 566 ...
Processing file 3 of 566 ...
Processing file 4 of 566 ...
Processing file 5 of 566 ...
Processing file 6 of 566 ...
Processing file 7 of 566 ...
[*...snip...*] 

частичные результаты на экране ...

Hash                             Path
----                             ----
D41D8CD98F00B204E9800998ECF8427E C:\temp\2018-11-17_22-00-00_-_TimeTest.txt
DD9972A59154D439B807217B40F7B569 C:\temp\au-descriptor-1.8.0_191-b12.xml
358D74CA3FB4A8DB01D2C1AB8BD7A0B5 C:\temp\CleanedVersion.log
33F2B09E2D9DFB732FA16B5F05A5A8D1 C:\temp\Enable1_WordList_File.txt
96B2DBFAE3F0353BF9FE5D87DD922C11 C:\temp\Func_Get-Name.ps1
__Error__                        C:\temp\FXSAPIDebugLogFile.txt
2E31A9B8BE6203D7636ED9E6A2B7D8CB C:\temp\Genre-List_2018-10-09.log
[*...snip...*] 

частичное содержимое файла CSV ...

"Hash","Path"
"D41D8CD98F00B204E9800998ECF8427E","C:\temp\2018-11-17_22-00-00_-_TimeTest.txt"
"DD9972A59154D439B807217B40F7B569","C:\temp\au-descriptor-1.8.0_191-b12.xml"
"358D74CA3FB4A8DB01D2C1AB8BD7A0B5","C:\temp\CleanedVersion.log"
"33F2B09E2D9DFB732FA16B5F05A5A8D1","C:\temp\Enable1_WordList_File.txt"
"5E6D32360C0A701B7A211C2AED5DD928","C:\temp\FileHashListing.csv"
"96B2DBFAE3F0353BF9FE5D87DD922C11","C:\temp\Func_Get-Name.ps1"
"__Error__","C:\temp\FXSAPIDebugLogFile.txt"
"2E31A9B8BE6203D7636ED9E6A2B7D8CB","C:\temp\Genre-List_2018-10-09.log"
[*...snip...*] 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...