powershell-devops.psm1

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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
New-Alias -Name set-env -Value Set-EnvironmentVariable
New-Alias -Name get-env -Value Get-EnvironmentVariable

function Test-AdoPipeline {
    [OutputType([bool])]
    [CmdletBinding()]
    param()
    return ![string]::IsNullOrEmpty($env:TF_BUILD)
}

function Test-GitHubWorkflow {
    [OutputType([bool])]
    [CmdletBinding()]
    param()
    return ![string]::IsNullOrEmpty($env:GITHUB_ACTIONS)
}

function Set-EnvironmentVariable {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position=0)]
        [ValidateNotNullOrEmpty()]
        [string] $Name,

        [Parameter(Mandatory, Position=1, ValueFromPipeline)]
        $Value,

        [switch] $Secret = $false,
        [switch] $Output = $false
    )

    if (Test-AdoPipeline) {
        Write-Host "##vso[task.setvariable variable=$Name;$($Secret ? 'issecret=true;' : '')$($Output ? 'isoutput=true;' : '')]$Value"
    } elseif (Test-GitHubWorkflow) {
        if ($Secret) {
            Write-Host "::add-mask::$Value"
        }
        if ($Output) { 
            Write-Host "::set-output name=$Name::$Value"
        } else {
            "$Name=$Value" | Out-File -FilePath $env:GITHUB_ENV -Append
        }
    }

    Set-Item -Path env:$Name -Value $Value -Force
}

function Get-EnvironmentVariable {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position=0)]
        [ValidateNotNullOrEmpty()]
        [string] $Name,

        [switch] $Require = $false
    )

    if (Test-Path -Path env:$Name -PathType Leaf) {
        (Get-Item -Path env:$Name).Value
    } elseif ($Require) {
        throw "The environment variable '$Name' is missing or undefined."
    }
}

function Enter-Group {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position=0)]
        [ValidateNotNullOrEmpty()]
        [string] $Name
    )

    if (Test-AdoPipeline) {
        Write-Host "##[group]$Name"
    } elseif (Test-GitHubWorkflow) {
        Write-Host "::group::$Name"
    }
}

function Exit-Group {
    [CmdletBinding()]
    param ()
    
    if (Test-AdoPipeline) {
        Write-Host '##[endgroup]'
    } elseif (Test-GitHubWorkflow) {
        Write-Host '::endgroup::'
    }   
}

function Add-Path {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position=0)]
        [ValidateNotNullOrEmpty()]
        [string] $Path
    )
    
    if (Test-AdoPipeline) {
        Write-Host "##vso[task.prependpath]$Path"
    } elseif (Test-GitHubWorkflow) {
        $Path >> $env:GITHUB_PATH
    }

    $env:PATH = "$Path;$env:PATH"
}