Powershell Progress Bar

2019-08-10 03:57发布

I'm new to Powershell and am having a problem getting a progress bar to work with a foreach-object loop (If it is even possible)

Thanks to Chris below is what I have so far, my problem here is that the progress bar gets to a point and then I get error: The 101 argument is greater than the maximum allowed range of 100:

$FolderList = Get-Content C:\Folders.txt
$i = 0

foreach( $Folder in $FolderList )
{

Write-Host $Folder
Get-ChildItem $Folder -Recurse *.pdf | foreach-object{

$fileCount = (Get-ChildItem $Folder).Count
$i += 1
Write-Progress -Activity "Counting Files" -status "Searching...." -percentComplete (($i / $fileCount)*100)

$pdf = c:\pdftk.exe $_.FullName dump_data
$NumberOfPages = [regex]::match($pdf,'NumberOfPages: (\d+)').Groups[1].Value

    New-Object PSObject -Property @{
    Name = $_.Name
    FullName = $_.FullName
    NumberOfPages = $NumberOfPages 
     } 
   } 
 }

1条回答
甜甜的少女心
2楼-- · 2019-08-10 04:43

Here's my approach to the problem:

$i = 0
$pdfFiles = @()

#First, get the files and add them to a collection:
foreach ($folder in $FolderList){
    Get-ChildItem $Folder -Recurse *.pdf | %{$pdfFiles += $_}
}

#Measure the collection
$fileCount = ($pdfFiles | Measure-Object).Count

#Do work on the collection
$pdfFiles | foreach-object{
    $pdf = c:\pdftk.exe $_.FullName dump_data
    $NumberOfPages = [regex]::match($pdf,'NumberOfPages: (\d+)').Groups[1].Value
    New-Object PSObject -Property @{
        Name = $_.Name
        FullName = $_.FullName
        NumberOfPages = $NumberOfPages 
    }
    $i += 1
    Write-Progress -Activity "Counting Files" -status "Searching...." -percentComplete (($i / $fileCount)*100)
}
查看更多
登录 后发表回答