internal/functions/Write-ProgressHelper.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function Write-ProgressHelper {
    # thanks adam!
    # https://www.adamtheautomator.com/building-progress-bar-powershell-scripts/
    param (
        [int]$StepNumber,
        [string]$Activity,
        [string]$Message,
        [int]$TotalSteps,
        [switch]$ExcludePercent
    )

    $caller = (Get-PSCallStack)[1].Command

    if (-not $Activity) {
        $Activity = switch ($caller) {
            "Export-DbaInstance" {
                "Performing Instance Export for $instance"
            }
            "Install-DbaSqlWatch" {
                "Installing SQLWatch"
            }
            "Invoke-DbaDbLogShipRecovery" {
                "Performing log shipping recovery"
            }
            "Invoke-DbaDbLogShipRecovery" {
                "Performing log shipping recovery"
            }
            "Invoke-DbaDbMirroring" {
                "Setting up mirroring"
            }
            "New-DbaAvailabilityGroup" {
                "Adding new availability group"
            }
            "Sync-DbaAvailabilityGroup" {
                "Syncing availability group"
            }
            "Sync-DbaAvailabilityGroup" {
                "Syncing availability group"
            }
            default {
                "Executing $caller"
            }
        }
    }

    if ($ExcludePercent) {
        Write-Progress -Activity $Activity -Status $Message
    } else {
        if (-not $TotalSteps -and $caller -ne '<ScriptBlock>') {
            $TotalSteps = ([regex]::Matches((Get-Command -Module dbatools -Name $caller).Definition, "Write-ProgressHelper")).Count
        }
        if (-not $TotalSteps) {
            $percentComplete = 0
        } else {
            $percentComplete = ($StepNumber / $TotalSteps) * 100
        }
        Write-Progress -Activity $Activity -Status $Message -PercentComplete $percentComplete
    }
}