Private/Write-AtwsProgress.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<#
 
    .COPYRIGHT
    Copyright (c) ECIT Solutions AS. All rights reserved. Licensed under the MIT license.
    See https://github.com/ecitsolutions/Autotask/blob/master/LICENSE.md for license information.
 
#>


Function Write-AtwsProgress {
    <#
      .SYNOPSIS
      This function emulates a very simple Write-Progress when running under VSCode, otherwise it just calls
      Write-Progress.
      .DESCRIPTION
      This function emulates a very simple Write-Progress when running under VSCode, otherwise it just calls
      Write-Progress.
      .INPUTS
      Nothing, only parameters.
      .OUTPUTS
      Text or calls Write-Progress
      .NOTES
      NAME: Write-AtwsProgress
       
  #>

    [cmdletbinding()]
    Param
    (
        [string]$Activity,
        [string]$Status,
        [int]$Id,
        [int]$PercentComplete,
        [int]$SecondsRemaining,
        [string]$CurrentOperation,
        [int]$ParentID,
        [switch]$Completed,
        [int]$SourceId
    )

    begin {
        # Enable modern -Debug behavior
        if ($PSCmdlet.MyInvocation.BoundParameters['Debug'].IsPresent) {
            $DebugPreference = 'Continue'
        }

        # Progress bar length in characters
        $size = 30
        Write-Debug ('{0}: Begin of function' -F $MyInvocation.MyCommand.Name)
    }

    process {
        if ($env:TERM_PROGRAM -eq 'vscode' -and $PSVersionTable.PSVersion.Major -le 8) {
            # Running in VSCode. Do our own stuff.
            $i = [Math]::Round($PercentComplete / (100 / $size))
            $string = $CurrentOperation.substring(0, [System.Math]::Min(39, $CurrentOperation.Length))
            $Message = "`r[{2}] {1,3} % - {0,-39}" -f $string, $PercentComplete, (''.PadLeft($i, '#') + ''.PadLeft($size - $i, '-'))

            # When using -NoNewLine this will be overwritten by -Verbose and/or -Debug
            Write-Host $Message -ForegroundColor Green -NoNewline
            
            if ($Completed.IsPresent) {
                # End the line. Looks better.
                Write-Host "`n"
            }
            
            # Repeat message if -Verbose is on
            Write-Verbose $Message
        }
        else {
            # Write-Progress should be supported. Pass all parameters to Write-Progress
            Write-Progress @PSBoundParameters
        }
        Write-Verbose ('{0}: Converting datetime to {1}' -F $MyInvocation.MyCommand.Name, $value)
        
    }

    end {
        Write-Debug ('{0}: End of function' -F $MyInvocation.MyCommand.Name)
    }
}