Repository navigation
Expand file tree
/
Copy pathMSIX.Scripts.ps1
More file actions
459 lines (385 loc) · 17.2 KB
/
Copy pathMSIX.Scripts.ps1
File metadata and controls
459 lines (385 loc) · 17.2 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# =============================================================================
# Standard scripts (PSADT-flavoured)
# -----------------------------------------------------------------------------
# Renders parameterised .ps1 scripts from the templates\ folder, optionally
# signs them, and (via Add-MsixStandardScript) wires them into a package as a
# PSF startScript.
#
# Templates use <#PARAM:Name#> placeholders; replacements happen in-memory and
# the output goes to the path you choose.
# =============================================================================
$script:TemplateDir = Join-Path -Path $PSScriptRoot -ChildPath 'templates'
# Catalogue: name -> { Template, Description, RequiredParams }
$script:StandardScriptCatalogue = [ordered]@{
CreateShortcut = @{
Template = 'CreateShortcut.ps1.tmpl'
Description = 'Create a desktop / start-menu shortcut to the packaged app on first launch.'
RequiredParams = @('DisplayName','Target')
Defaults = @{
Arguments = ''
WorkingDirectory = ''
IconPath = ''
Location = 'Desktop'
}
}
CopyIconToAppData = @{
Template = 'CopyIconToAppData.ps1.tmpl'
Description = 'Copy bundled icon(s) into %APPDATA% so shortcuts survive package updates.'
RequiredParams = @('SourceFiles','DestSubfolder')
Defaults = @{}
}
CleanupOldUserData = @{
Template = 'CleanupOldUserData.ps1.tmpl'
Description = 'Idempotent removal of legacy user-state directories and registry keys.'
RequiredParams = @()
Defaults = @{
Paths = ''
RegistryKeys = ''
OnlyOlderThanDays= '0'
}
}
RegisterFileAssociation = @{
Template = 'RegisterFileAssociation.ps1.tmpl'
Description = 'Register a host-side file association under HKCU pointing at an alias.'
RequiredParams = @('Extensions','ProgId','Target')
Defaults = @{ Arguments = '' }
}
CustomerSettingsBootstrap = @{
Template = 'CustomerSettingsBootstrap.ps1.tmpl'
Description = 'Bake in customer-specific HKCU settings as JSON; written on first launch.'
RequiredParams = @('HivePath','Settings')
Defaults = @{ Overwrite = 'false' }
}
}
function Get-MsixStandardScript {
<#
.SYNOPSIS
Lists the standard-script templates this module ships with.
.DESCRIPTION
Returns one entry per template in the module's templates\ folder. The
catalogue is used as input to New-MsixStandardScript and
Add-MsixStandardScript and lists the placeholder parameters that
each template needs (RequiredParams) and the ones it accepts
optionally (OptionalParams, with defaults).
The module currently ships five PSADT-flavoured templates:
CreateShortcut, CopyIconToAppData, CleanupOldUserData,
RegisterFileAssociation, CustomerSettingsBootstrap.
.OUTPUTS
[pscustomobject] one per template, with Name, Description,
RequiredParams, OptionalParams, Template (full path on disk).
.EXAMPLE
Get-MsixStandardScript | Format-Table Name, Description
.EXAMPLE
# Inspect the placeholders for a specific template
Get-MsixStandardScript | Where-Object Name -eq 'CreateShortcut'
#>
[CmdletBinding()]
param()
foreach ($k in $script:StandardScriptCatalogue.Keys) {
$v = $script:StandardScriptCatalogue[$k]
[pscustomobject]@{
Name = $k
Description = $v.Description
RequiredParams = $v.RequiredParams
OptionalParams = @($v.Defaults.Keys)
Template = Join-Path -Path $script:TemplateDir -ChildPath $v.Template
}
}
}
function _MsixRenderTemplate {
param(
[string]$TemplatePath,
[hashtable]$Parameters
)
if (-not (Test-Path -LiteralPath $TemplatePath)) { throw "Template not found: $TemplatePath" }
# Read as UTF-8 explicitly. Get-Content with no -Encoding falls back to the
# ANSI code page on Windows PowerShell 5.1, and the bundled .tmpl files are
# BOM-less UTF-8 containing non-ASCII - so 5.1 mis-decoded them as CP-1252
# and wrote mojibake into generated, code-signed customer scripts. .tmpl is
# outside the repo's BOM rule and PSSA's check, so it slipped through (#146).
$text = [IO.File]::ReadAllText($TemplatePath, [Text.UTF8Encoding]::new($false))
# Find every <#PARAM:Name#> in the template, replace from $Parameters,
# complain about anything left unsubstituted.
$pattern = '<#PARAM:([A-Za-z0-9_]+)#>'
$needed = [regex]::Matches($text, $pattern) | ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique
foreach ($name in $needed) {
if (-not $Parameters.ContainsKey($name)) {
throw "Template '$TemplatePath' requires -$name but it was not provided."
}
# SECURITY: every <#PARAM:#> placeholder in the bundled templates sits
# inside a single-quoted PowerShell string literal (e.g.
# $displayName = '<#PARAM:DisplayName#>'). A raw substitution of a value
# containing a single quote would terminate that literal and inject
# arbitrary PowerShell into the generated — and subsequently
# code-signed — script. Doubling embedded single quotes keeps the value
# a literal within its single-quoted context. A newline is harmless
# inside a single-quoted literal, so quote-doubling is the complete fix.
$value = ([string]$Parameters[$name]).Replace("'", "''")
# Literal (non-regex) placeholder replacement.
$text = $text.Replace("<#PARAM:$name#>", $value)
}
return $text
}
function New-MsixStandardScript {
<#
.SYNOPSIS
Generates a customised PowerShell script from a bundled template.
.DESCRIPTION
Picks one of the standard templates, substitutes parameters, writes
the result to disk. Optionally signs the resulting .ps1 with a
provided code-signing certificate so the package can run it under
AllSigned/RemoteSigned execution policies.
See Get-MsixStandardScript for the list of templates.
.PARAMETER Name
Template name (e.g. 'CreateShortcut').
.PARAMETER Parameters
Hashtable of placeholder values (e.g. @{ DisplayName='Foo'; Target='foo.exe' }).
.PARAMETER OutputPath
Where to write the generated .ps1.
.PARAMETER Pfx
Path to a code-signing PFX. If supplied, the rendered script is signed
via Set-MsixScriptSignature. Omit to leave the script unsigned.
.PARAMETER PfxPassword
SecureString password for the PFX. Required when -Pfx is supplied.
.PARAMETER TimestampUrl
RFC 3161 timestamp server. Default: http://timestamp.digicert.com.
.OUTPUTS
[System.IO.FileInfo] for the generated .ps1.
.EXAMPLE
New-MsixStandardScript -Name CreateShortcut `
-Parameters @{ DisplayName='Contoso Expenses'; Target='contosoexpenses.exe' } `
-OutputPath C:\src\createshortcut.ps1 `
-Pfx cert.pfx -PfxPassword (Read-Host -AsSecureString)
.EXAMPLE
# Render unsigned, for local testing
New-MsixStandardScript -Name CleanupOldUserData `
-Parameters @{ Paths='%AppData%\Contoso\v1'; OnlyOlderThanDays='30' } `
-OutputPath .\cleanup.ps1
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[ValidateScript({ $_ -in $script:StandardScriptCatalogue.Keys })]
[string]$Name,
[Parameter(Mandatory)]
[hashtable]$Parameters,
[Parameter(Mandatory)]
[string]$OutputPath,
[string]$Pfx,
[SecureString]$PfxPassword,
[string]$TimestampUrl = 'http://timestamp.digicert.com'
)
$entry = $script:StandardScriptCatalogue[$Name]
foreach ($req in $entry.RequiredParams) {
if (-not $Parameters.ContainsKey($req) -or [string]::IsNullOrEmpty($Parameters[$req])) {
throw "Template '$Name' requires -$req."
}
}
# Apply defaults
$merged = @{}
foreach ($k in $entry.Defaults.Keys) { $merged[$k] = $entry.Defaults[$k] }
foreach ($k in $Parameters.Keys) { $merged[$k] = $Parameters[$k] }
$tmpl = Join-Path -Path $script:TemplateDir -ChildPath $entry.Template
$content = _MsixRenderTemplate -TemplatePath $tmpl -Parameters $merged
if ($PSCmdlet.ShouldProcess($OutputPath, "Generate $Name from template")) {
$dir = Split-Path -Path $OutputPath -Parent
if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -Path $dir -ItemType Directory -Force | Out-Null }
# BOM: this is a generated .ps1 that ships inside customer packages and
# is code-signed. Windows PowerShell 5.1 reads a BOM-less UTF-8 file as
# CP-1252, so non-ASCII content would be corrupted (issue #146).
_MsixWriteUtf8 -Path $OutputPath -Text $content -WithBom
Write-MsixLog -Level Info -Message "Generated $Name -> $OutputPath"
}
if ($Pfx) {
Set-MsixScriptSignature -ScriptPath $OutputPath -Pfx $Pfx -PfxPassword $PfxPassword -TimestampUrl $TimestampUrl
}
return Get-Item -LiteralPath $OutputPath
}
function Set-MsixScriptSignature {
<#
.SYNOPSIS
Signs a PowerShell script (Authenticode + RFC 3161 timestamp) using the
same certificate the rest of the module uses for package signing.
.DESCRIPTION
Wraps Set-AuthenticodeSignature so callers don't have to deal with
certificate loading / timestamp server arguments.
.PARAMETER ScriptPath
The .ps1 (or .psm1) file to sign.
.PARAMETER Pfx
Path to the PFX certificate. Required.
.PARAMETER PfxPassword
SecureString password for the PFX. Required.
.PARAMETER TimestampUrl
RFC 3161 server. Default: http://timestamp.digicert.com.
.OUTPUTS
[System.Management.Automation.Signature] returned by
Set-AuthenticodeSignature.
.EXAMPLE
Set-MsixScriptSignature -ScriptPath .\createshortcut.ps1 `
-Pfx .\cert.pfx -PfxPassword (Read-Host -AsSecureString)
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
param(
[Parameter(Mandatory)]
[string]$ScriptPath,
[Parameter(Mandatory)]
[string]$Pfx,
[Parameter(Mandatory)]
[SecureString]$PfxPassword,
[string]$TimestampUrl = 'http://timestamp.digicert.com'
)
if (-not (Test-Path -LiteralPath $ScriptPath)) { throw "Script not found: $ScriptPath" }
if (-not (Test-Path -LiteralPath $Pfx)) { throw "PFX not found: $Pfx" }
# Construct the certificate directly instead of Get-PfxCertificate -Password:
# that parameter was added in PowerShell 6 and does NOT exist on Windows
# PowerShell 5.1, where it threw "A parameter cannot be found that matches
# parameter name 'Password'" and made this function - and
# Add-MsixStandardScript -Pfx, which calls it - unusable (issue #146).
# The SecureString is never converted to plaintext; the X509 constructor
# takes it directly. UserKeySet keeps the key out of the machine store.
$pfxPath = (Resolve-Path -LiteralPath $Pfx).ProviderPath
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 `
-ArgumentList $pfxPath, $PfxPassword,
([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet)
try {
$sig = Set-AuthenticodeSignature -FilePath $ScriptPath -Certificate $cert `
-TimestampServer $TimestampUrl `
-HashAlgorithm SHA256 -ErrorAction Stop
} finally {
if ($cert) { $cert.Dispose() }
}
if ($sig.Status -ne 'Valid') {
Write-MsixLog -Level Warning -Message "Script signature status: $($sig.Status) ($($sig.StatusMessage))"
} else {
Write-MsixLog -Level Info -Message "Signed: $ScriptPath ($($sig.SignerCertificate.Thumbprint))"
}
return $sig
}
function Add-MsixStandardScript {
<#
.SYNOPSIS
High-level: generate a standard script, sign it, and inject it into an
MSIX package as a PSF startScript in one call.
.DESCRIPTION
Combines New-MsixStandardScript + Add-MsixPsfV2 -AppOptions /
-AdditionalFiles. The signing certificate is shared between the script
and the package so they form a coherent signed artefact.
.PARAMETER PackagePath
The .msix file to modify.
.PARAMETER AppId
Application Id to attach the startScript to.
.PARAMETER Name
Standard-script template name (see Get-MsixStandardScript).
.PARAMETER Parameters
Hashtable of values to substitute into the template.
.PARAMETER ScriptFileName
Name of the .ps1 inside the package (default: <Name>.ps1).
.PARAMETER RunOnce
Forwarded to New-MsixPsfStartScriptConfig. Run the script only on the
first launch of the app.
.PARAMETER WaitForScriptToFinish
Forwarded to New-MsixPsfStartScriptConfig. Block app launch until the
startScript exits.
.PARAMETER ShowWindow
Forwarded to New-MsixPsfStartScriptConfig. Show the script's console
window (otherwise hidden).
.PARAMETER RunInVirtualEnvironment
Forwarded to New-MsixPsfStartScriptConfig. Run the script inside the
package's virtual environment.
.PARAMETER StopOnScriptError
Forwarded to New-MsixPsfStartScriptConfig. Abort app launch if the
script returns a non-zero exit code.
.PARAMETER Timeout
Forwarded to New-MsixPsfStartScriptConfig. Timeout in seconds. 0 = no
timeout (default).
.PARAMETER EndScript
Forwarded to New-MsixPsfStartScriptConfig. Treat the script as an
endScript instead of a startScript.
.PARAMETER Pfx
Path to the code-signing PFX. Used for BOTH the rendered .ps1 and
the repacked .msix.
.PARAMETER PfxPassword
SecureString password for -Pfx.
.PARAMETER OutputPath
Forwarded to Add-MsixPsfV2. Where to write the repacked .msix.
Defaults to overwriting -PackagePath.
.PARAMETER SkipSigning
Forwarded to Add-MsixPsfV2. Skip signing of both the script and the
package. Alias: -NoSign.
.OUTPUTS
[pscustomobject] returned by Add-MsixPsfV2 (PackagePath, fixups list,
etc.).
.EXAMPLE
Add-MsixStandardScript -PackagePath .\app.msix -AppId 'App' `
-Name CreateShortcut `
-Parameters @{ DisplayName='Contoso'; Target='contoso.exe' } `
-RunOnce -WaitForScriptToFinish `
-Pfx .\cert.pfx -PfxPassword (Read-Host -AsSecureString)
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$PackagePath,
[Parameter(Mandatory)]
[string]$AppId,
[Parameter(Mandatory)]
[ValidateScript({ $_ -in $script:StandardScriptCatalogue.Keys })]
[string]$Name,
[Parameter(Mandatory)]
[hashtable]$Parameters,
[string]$ScriptFileName,
[switch]$RunOnce,
[switch]$WaitForScriptToFinish,
[switch]$ShowWindow,
[switch]$RunInVirtualEnvironment,
[switch]$StopOnScriptError,
[int]$Timeout = 0,
[switch]$EndScript,
[string]$Pfx,
[SecureString]$PfxPassword,
[string]$OutputPath,
[Alias('NoSign')]
[switch]$SkipSigning
)
if (-not $ScriptFileName) { $ScriptFileName = "$Name.ps1" }
# Stage script in a workspace so cleanup is easy
$stage = New-MsixWorkspace -PackageName "$AppId-$Name"
$scriptPath = Join-Path -Path $stage -ChildPath $ScriptFileName
try {
$genArgs = @{
Name = $Name
Parameters = $Parameters
OutputPath = $scriptPath
}
if ($Pfx -and -not $SkipSigning) {
$genArgs['Pfx'] = $Pfx
$genArgs['PfxPassword'] = $PfxPassword
}
New-MsixStandardScript @genArgs | Out-Null
$startBlock = New-MsixPsfStartScriptConfig -AppId $AppId `
-ScriptPath $ScriptFileName `
-RunOnce:$RunOnce `
-WaitForScriptToFinish:$WaitForScriptToFinish `
-ShowWindow:$ShowWindow `
-RunInVirtualEnvironment:$RunInVirtualEnvironment `
-StopOnScriptError:$StopOnScriptError `
-Timeout $Timeout `
-EndScript:$EndScript
$psfArgs = @{
PackagePath = $PackagePath
Fixups = @()
AppOptions = @($startBlock)
AdditionalFiles = @($scriptPath)
}
if ($Pfx) { $psfArgs['Pfx'] = $Pfx }
if ($PfxPassword) { $psfArgs['PfxPassword'] = $PfxPassword }
if ($OutputPath) { $psfArgs['OutputPath'] = $OutputPath }
if ($SkipSigning) { $psfArgs['SkipSigning'] = $true }
Add-MsixPsfV2 @psfArgs
} finally {
Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
}
}
# Backward-compatible plural aliases
Set-Alias Get-MsixStandardScripts Get-MsixStandardScript