Set-Tokens.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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#Set-StrictMode -Version Latest
#####################################################
# Set-Tokens
#####################################################
<#PSScriptInfo
 
.VERSION 0.13
 
.GUID bfd55243-60dd-4394-a80e-835718187e1f
 
.AUTHOR David Walker, Sitecore Dave, Radical Dave
 
.COMPANYNAME David Walker, Sitecore Dave, Radical Dave
 
.COPYRIGHT David Walker, Sitecore Dave, Radical Dave
 
.TAGS powershell sitecore package
 
.LICENSEURI https://github.com/SharedSitecore/Set-Tokens/blob/main/LICENSE
 
.PROJECTURI https://github.com/SharedSitecore/Set-Tokens
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
#>


<#
 
.DESCRIPTION
 PowerShell Script to set/replace tokens in strings and files
 
.PARAMETER name
Path of package
 
#>
 
#####################################################
# Set-Tokens
#####################################################

[CmdletBinding(SupportsShouldProcess)]
Param(
    [Parameter(Mandatory=$false)]
    [string] $source,
    [Parameter(Mandatory=$false)]
    [string] $destination,
    [Parameter(Mandatory=$false)]
    [string] $regex = '(\$\()([a-zA-Z0-9\.\-_]*)(\))'
)
begin {
    $ProgressPreference = 'SilentlyContinue'
    $ErrorActionPreference = 'Stop'
    $PSScriptVerson = (Test-ScriptFileInfo -Path $MyInvocation.MyCommand.Path | Select-Object -ExpandProperty Version)
    $PSScriptName = ($MyInvocation.MyCommand.Name.Replace('.ps1',''))
    $PSCallingScript = if ($MyInvocation.PSCommandPath) { $MyInvocation.PSCommandPath | Split-Path -Parent } else { $null }
    $currLocation = "$(Get-Location)"
    Write-Verbose "$PSScriptName $PSScriptVerson $source $destination called by:$PSCallingScript from $currLocation"

    function Set-TokenContent($string) {
        if (!$string) { return $string }
        $results = $string
        $tokens = [regex]::Matches($string,$regex)
        if (!$tokens) {
            return $string
        }
        $tokensfound = @{}
        $tokens | Foreach-Object {            
            $org = $_.groups[0].value
            $token = $org
            #Write-Verbose "token:$token"
            if ($token -like '$(*') {
                $token = $token.Remove(0,2) 
                $token = $token.Substring(0, $token.Length - 1)
            }
            $value = [System.Environment]::GetEnvironmentVariable($token)
            #Write-Verbose "Set-TokenContent:$token=$value"
            $tokensfound[$token] = $value
            $results = $results.replace($org,$value)
        }
        Write-Verbose "Tokens updated:"
        $tokensfound.keys.foreach({
            Write-Verbose "$($_):$($tokensfound[$_])"
        })
        return $results
    }

    #TODO - extract to own script or finish inclusion in Set-Env with Nick
    function Set-Envs($path) {
        try {
            if ($path) {
                #Write-Verbose "checking:$path\*.env*"
                if (Test-Path $path\*.env*) {
                    Get-ChildItem â€“Path $path\*.env* | Foreach-Object {
                        try {
                            $f = $_
                            #Write-Verbose "checking:$($f.FullName)"
                            $content = (Get-Content $f.FullName)
                            $content | ForEach-Object {
                                if (-not ($_ -like '#*') -and  ($_ -like '*=*')) {
                                    $sp = $_.Split('=')
                                    #Write-Verbose "Set-Env $($sp[0])=$($sp[1])"
                                    #$env:${$sp[0]} = $sp[1]
                                    #$scope = System.EnvironmentVariableTarget]::User
                                    #$scope = System.EnvironmentVariableTarget]::Session
                                    #$scope = System.EnvironmentVariableTarget]::Machine
                                    #[System.Environment]::SetEnvironmentVariable($sp[0], $sp[1], $scope)
                                    [System.Environment]::SetEnvironmentVariable($sp[0], $sp[1])                                    
                                    #Write-Verbose "Set-Env $($sp[0])=$($sp[1]):set"
                                }
                            }
                        }
                        catch {
                            Write-Error "ERROR Set-Env $path-$f" -InformationVariable results
                        }
                    }
                } else { 
                    #Write-Verbose "skipped:$p no *.env* files found"
                }
            }
        }
        catch {
            Write-Error "ERROR Set-Env $path" -InformationVariable results
        }
    }
 
    if (!$source) { $source = "$currLocation\*.json" }
    if (-not (Test-Path $source)) {
        Write-Host "$PSScriptName skipped - empty source:$source"
        return "$PSScriptName skipped - empty source:$source"
    }
    #Write-Verbose "source:$source"
    #Write-Verbose "destination:$destination"
    if (!$destination) {$destination = $source} elseif ($destination.IndexOf(':') -eq -1 -and $destination.Substring(0,1) -ne '\') {$destination = Join-Path $currLocation $destination}
    #Write-Verbose "destination:$destination"
    if ($destination) {
        if (-not (Test-Path $source -PathType Leaf)) {
            if (-not (Test-Path $destination)) { New-Item -Path $destination -ItemType Directory | Out-Null}            
        } else {
            $destParent = Split-Path $destination -Parent
            if (-not (Test-Path $destParent)) { New-Item -Path $destParent -ItemType Directory | Out-Null}
        }
    }

    @((Split-Path $profile -Parent),$PSScriptRoot,("$currLocation" -ne "$PSScriptRoot" ? $currLocation : ''),(Split-Path $source -Parent),($destination -ne $source -and $destParent) ? $destParent : ''