Function Powershell:正在创建的文件夹的进度条

Function Powershell:正在创建的文件夹的进度条,function,powershell,loops,Function,Powershell,Loops,我正在尝试查看是否可以根据脚本的持续时间或它正在创建的文件夹来启动进度条 该脚本正在构建一个大文件夹结构的框架。我想在脚本中加入一个进度条。到目前为止,我掌握的情况如下: $Progress = @{ Activity = 'Building Source Folders' CurrentOperation = "Verifying/Building" PercentComplete = 0 } Write-Progress @Progress $u = 0 ForE

我正在尝试查看是否可以根据脚本的持续时间或它正在创建的文件夹来启动进度条

该脚本正在构建一个大文件夹结构的框架。我想在脚本中加入一个进度条。到目前为止,我掌握的情况如下:

$Progress = @{
    Activity = 'Building Source Folders'
    CurrentOperation = "Verifying/Building"
    PercentComplete = 0
}

Write-Progress @Progress
$u = 0

ForEach ($f in $folders) {
$folders = Get-ChildItem C:\Source -Recurse
$u++
[int]$percentage = ($u / $folders.count)*100
$progress.CurrentOperation = "$f"
$progress.PercentComplete = $percentage

Write-Progress @Progress
}

rest of the script

非常感谢您的帮助,因为我不知道将其作为循环是否是执行进度条的唯一方法,或者是否最好将其作为函数来执行。

我认为您的问题是,在循环中有Get ChildItem调用,这没有意义,也不起作用。把它拉到外面应该行得通:

$Progress = @{
    Activity = 'Building Source Folders'
    CurrentOperation = "Verifying/Building"
    PercentComplete = 0
}

Write-Progress @Progress
$u = 0

$folders = Get-ChildItem C:\Source -Recurse

ForEach ($f in $folders) {
    $u++
    [int]$percentage = ($u / $folders.count)*100
    $progress.CurrentOperation = "$f"
    $progress.PercentComplete = $percentage

    Write-Progress @Progress
}

根据我们在这里讨论的文件夹数量,值得考虑对性能的影响。写进度相当慢

在我的机器上,10000次写进度调用使用以下代码需要10秒:

Measure-Command {
    for( $i = 0; $i -lt 10000; $i++ ) {
        Write-Progress -Activity '' -Status "$i of 10,000" -Id 1 -PercentComplete 0
    }
}
一种选择是执行检查,并且只每隔一段时间执行一次写入进度。此版本每100次迭代执行一次(因此100次写进度调用),此代码在我的计算机上运行时间为.046秒:

Measure-Command {
    for( $i = 0; $i -lt 10000; $i++ ) {
        # Only do a Write-Progress on every 100th loop iteration
        if( $i % 100 -eq 0 )
        {
            Write-Progress -Activity '' -Status "$i of 10,000" -Id 1 -PercentComplete 0
        }
    }
}

我最终从以下代码获得了我想要的:


我没有看到在您的代码中创建任何文件夹。@Theo我没有包括它,因为它只是一堆
if
语句,后跟
newitem
命令,如果文件夹不存在,则创建文件夹
$steps = ([System.Management.Automation.PsParser]::Tokenize($MyInvocation.MyCommand.Definition, [ref]$null) | where { $_.Type -eq 'Command' -and $_.Content -eq 'Progress-Bar' }).Count
$StepCounter = 0

function Progress-Bar {
    param(
        [int]$StepNumber,
        [string]$Message,
        [string]$Percent = "$(([math]::Round((($StepCounter)/$steps * 100)))) %"
    )

    Write-Progress -Activity 'Building TDC Source Folder Structure' -Status $Message -CurrentOperation $Percent -PercentComplete (($StepNumber / $steps) * 100)
}```