-
Notifications
You must be signed in to change notification settings - Fork 0
/
CreateManifestAndConfigForPSF.ps1
367 lines (309 loc) · 14.7 KB
/
CreateManifestAndConfigForPSF.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
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
# CreateManifestAndConfigForPSF.ps1
#
# Description:
# Creates modified AppxManifest.xml (AppxManifestNew.xml) and config.json to facilitate the creating of Desktop Shortcuts
# Adds AppExecutionAlias for app (Needed for Desktop Shortcuts)
# Adding additional schema definition namespaces to support AppExecutionAlias
# Replaces Executable exe with psfLauncher exe - required since Desktop Shortcuts are created via script at first time launch
# Creates config.json entries for each application in AppxManifest.xml
#
# Requires:
# AppxManifest.xml from packaged app
#
# Output:
# AppxManifestNew.xml and config.json
# Contents of AppxManifestNew.xml and config.json file will be added to MSIX to create Desktop Shortcuts when app is run.
# CreateShortcuts.ps1, StartingScriptWrapper.ps1, and PSF binaries required. See blog post for details.
Function Export-Icons {
<#
.SYNOPSIS
It's ugly but it works.
.DESCRIPTION
Export-Icons exports high-quality icons stored within .DLL and .EXE files. The function can export to a number of formats, including
ico, bmp, png, jpg, gif, emf, exif, icon, tiff, and wmf. In addition, it can also export to a different size.
This function quickly exports *all* icons stored within the resource file.
.PARAMETER Path
Path to the .dll or .exe
.PARAMETER Directory
Directory where the exports should be stored. If no directory is specified, all icons will be exported to the TEMP directory.
.PARAMETER Size
This specifies the pixel size of the exported icons. All icons will be squares, so if you want a 16x16 export, it would be -Size 16.
Valid sizes are 8, 16, 24, 32, 48, 64, 96, and 128. The default is 32.
.PARAMETER Type
This is the type of file you would like to export to. The default is .ico
Valid types are ico, bmp, png, jpg, gif, emf, exif, icon, tiff, and wmf. The default is ico.
.NOTES
Author: Chrissy LeMaire
Requires: PowerShell 3.0
Version: 1.0
DateUpdated: 2015-Sept-16
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Export-Icon-from-DLL-and-9d309047
.EXAMPLE
Export-Icons C:\windows\system32\imageres.dll
Exports all icons stored witin C:\windows\system32\imageres.dll to $env:temp\icons. Creates directory if required and automatically opens output directory.
.EXAMPLE
Export-Icons -Path "C:\Program Files (x86)\VMware\Infrastructure\Virtual Infrastructure Client\Launcher\VpxClient.exe" -Size 64 -Type png -Directory C:\temp
Exports the high-quality icon within VpxClient.exe to a transparent png in C:\temp\. Resizes the exported image to 64x64. Creates directory if required
and automatically opens output directory.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$Path,
[string]$Directory,
[ValidateSet(8, 16, 24, 32, 48, 64, 96, 128)]
[int]$Size = 32,
[ValidateSet("ico", "bmp", "png", "jpg", "gif", "jpeg", "emf", "exif", "icon", "tiff", "wmf")]
[string]$Type = "ico",
[string]$iconFilename = "AppIcon"
)
BEGIN {
# Thanks Thomas Levesque at http://bit.ly/1KmLgyN and darkfall http://git.io/vZxRK
$code = '
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.IO;
namespace System {
public class IconExtractor {
public static Icon Extract(string file, int number, bool largeIcon) {
IntPtr large;
IntPtr small;
ExtractIconEx(file, number, out large, out small, 1);
try { return Icon.FromHandle(largeIcon ? large : small); }
catch { return null; }
}
[DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);
}
}
public class PngIconConverter
{
public static bool Convert(System.IO.Stream input_stream, System.IO.Stream output_stream, int size, bool keep_aspect_ratio = false)
{
System.Drawing.Bitmap input_bit = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(input_stream);
if (input_bit != null)
{
int width, height;
if (keep_aspect_ratio)
{
width = size;
height = input_bit.Height / input_bit.Width * size;
}
else
{
width = height = size;
}
System.Drawing.Bitmap new_bit = new System.Drawing.Bitmap(input_bit, new System.Drawing.Size(width, height));
if (new_bit != null)
{
System.IO.MemoryStream mem_data = new System.IO.MemoryStream();
new_bit.Save(mem_data, System.Drawing.Imaging.ImageFormat.Png);
System.IO.BinaryWriter icon_writer = new System.IO.BinaryWriter(output_stream);
if (output_stream != null && icon_writer != null)
{
icon_writer.Write((byte)0);
icon_writer.Write((byte)0);
icon_writer.Write((short)1);
icon_writer.Write((short)1);
icon_writer.Write((byte)width);
icon_writer.Write((byte)height);
icon_writer.Write((byte)0);
icon_writer.Write((byte)0);
icon_writer.Write((short)0);
icon_writer.Write((short)32);
icon_writer.Write((int)mem_data.Length);
icon_writer.Write((int)(6 + 16));
icon_writer.Write(mem_data.ToArray());
icon_writer.Flush();
return true;
}
}
return false;
}
return false;
}
public static bool Convert(string input_image, string output_icon, int size, bool keep_aspect_ratio = false)
{
System.IO.FileStream input_stream = new System.IO.FileStream(input_image, System.IO.FileMode.Open);
System.IO.FileStream output_stream = new System.IO.FileStream(output_icon, System.IO.FileMode.OpenOrCreate);
bool result = Convert(input_stream, output_stream, size, keep_aspect_ratio);
input_stream.Close();
output_stream.Close();
return result;
}
}
'
If (-not ("System.IconExtractor" -as [type])) {
Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing, System.IO -ErrorAction SilentlyContinue
}
}
PROCESS {
switch ($type) {
"jpg" { $type = "jpeg" }
"icon" { $type = "ico" }
}
# Ensure file exists
$path = Resolve-Path $path
if ((Test-Path $path) -eq $false) { throw "$path does not exist." }
# Ensure directory exists if one was specified. Otherwise, create icon directory in TEMP
if ($directory.length -eq 0) { $directory = "$env:temp\icons" }
if ((Test-Path $directory) -eq $false) {
try { New-Item -Type Directory $directory | Out-Null }
catch { throw "Can't create $directory" }
}
# Extract
$index = 0
$tempfile = "$directory\tempicon.png"
$basename = [io.path]::GetFileNameWithoutExtension($path)
do {
try { $icon = [System.IconExtractor]::Extract($path, $index, $true) }
catch { throw "Could not extract icon. Do you have the proper permissions?" }
if ($icon -ne $null) {
#Log-Write -Text "Icon extracted"
#$filepath = "$directory\$basename-$index.$type"
$filepath = "$directory\$iconFilename"
# Convert to bitmap, otherwise it's ugly
$bmp = $icon.ToBitmap()
try {
if ($type -eq "ico") {
$bmp.Save($tempfile, "png")
[PngIconConverter]::Convert($tempfile, $filepath, $size, $true) | Out-Null
# Keep remove-item from complaining about weird directories
cmd /c del $tempfile
Log-Write -Text "Icon converted to png for resizing."
}
else {
if ($bmp.Width -ne $size) {
# Needs to be resized
$newbmp = New-Object System.Drawing.Bitmap($size, $size)
$graph = [System.Drawing.Graphics]::FromImage($newbmp)
# Make it transparent
$graph.clear([System.Drawing.Color]::Transparent)
$graph.DrawImage($bmp, 0, 0, $size, $size)
#save to file
$newbmp.Save($filepath, $type)
$newbmp.Dispose()
}
else { $bmp.Save($filepath, $type) }
$bmp.Dispose()
}
$icon.Dispose()
$index++
}
catch { throw "Could not convert icon." }
}
} while ($icon -ne $null)
if ($index -eq 0) { Write-Error "No icons to extract :(" }
}
}
# Create config.json
$scriptJson = @{
scriptPath = 'CreateShortcuts.ps1'
}
$applications = @{
id = ''
executable = ''
arguments = ''
startScript = $scriptJson
}
$configjsonArray = [System.Collections.ArrayList]@()
# Get AppIds and Executable names from manifest to write to config.json
[xml]$manifest = get-content "AppxManifest.xml"
$appsInManifest= $manifest.Package.Applications.Application
foreach ($app in $appsInManifest) {
if ($app.VisualElements.AppListEntry -eq "none") {
continue
}
$object = new-object psobject -Property $applications
$object.id= $app.id;
$object.executable = $app.Executable;
$res=$configjsonArray.Add($object);
}
# Create config.json file
# config.json Application arguments
$header="{
`"applications`":["
$footer="]}"
$header | Out-File ($pwd.Path + "\config.json");
$configjsonArray | ConvertTo-Json | Out-File -Append ($pwd.Path + "\config.json");
# Write config.json
$footer | Out-File -Append ($pwd.Path + "\config.json");
# Add namespaces needed by AppExecutionAlias
$nsm = New-Object System.Xml.XmlNamespaceManager($manifest.nametable)
$nsList = @( ("uap3", "http://schemas.microsoft.com/appx/manifest/uap/windows10/3"), ("desktop", "http://schemas.microsoft.com/appx/manifest/desktop/windows10") )
$ignoreNS=$manifest.Package.IgnorableNamespaces;
foreach ($ns in $nsList) {
$nsm.AddNamespace($ns[0], $ns[1])
$manifest.Package.SetAttribute("xmlns:"+$ns[0], $ns[1])
$ignoreNS = $ignoreNS + " " + $ns[0]
}
$manifest.Package.RemoveAttribute("IgnorableNamespaces")
$manifest.Package.SetAttribute("IgnorableNamespaces", $ignoreNS)
# Determine which psf launcher is needed
$arch = $manifest.Package.Identity.ProcessorArchitecture
if ($arch -eq "x64") {
$psfLauncher='psflauncher64.exe'
} else {
$psfLauncher='psflauncher32.exe'
}
# Add appExecutionAlias for each exe in the manifest, except if AppListEntry='None'
# Create appExecutionAlias node
foreach ($app in $manifest.Package.Applications.Application) {
$el=$manifest.CreateElement("uap3:Extension", $nsm.LookupNamespace("uap3"))
$el.SetAttribute("Category", "windows.appExecutionAlias")
$el.SetAttribute("Executable", $psfLauncher)
$el.SetAttribute("EntryPoint", "Windows.FullTrustApplication")
$aliasEl=$manifest.CreateElement("uap3:AppExecutionAlias", $nsm.LookupNamespace("uap3"))
$appaliasEl=$manifest.CreateElement("desktop:ExecutionAlias", $nsm.LookupNamespace("desktop"))
# Note: Alias has same name as EXE
$res = $appaliasEl.SetAttribute("Alias", $($(Split-Path $app.Executable -Leaf).ToLower()))
$res= $aliasEl.AppendChild($appaliasEl)
$res= $el.AppendChild($aliasEl)
if ($null -eq $app.Extensions) {
$extensions= $manifest.CreateElement("Extensions")
$ext= $manifest.Package.Applications.Application.AppendChild($extensions)
$res = $ext.AppendChild($el)
$extensions.SetAttribute("xmlns", "http://schemas.microsoft.com/appx/manifest/foundation/windows10")
} else {
$app.Extensions.AppendChild($el)
}
}
# Set Executables in manifest to PSFLauncher
foreach ($app in $manifest.Package.Applications.Application) {
$app.SetAttribute("Executable", $psfLauncher);
}
# Write new manifest file
$manifest.Save($pwd.Path + "\AppxManifestNew.xml");
#Create Icons
$desinationIconPath = $($pwd.Path + "\Icons")
$res = Test-Path $desinationIconPath
if ($res -ne $true)
{
New-Item -Path $desinationIconPath -ItemType Directory
}
Function ExtractIcon {
Param (
[Parameter(Mandatory = $true)]
[string]$exePath,
[string]$destinationFolder,
[string]$iconName
)
$destIcon = $iconName + ".ico"
Export-Icons $exePath $destinationFolder 32 "ico" $destIcon
}
$index = 0;
Foreach ($app in $configjsonArray) {
$appPath = ($pwd.Path + "\" + $app.Executable)
try {
ExtractIcon -exePath ( $appPath ) -destinationFolder ( $desinationIconPath ) -iconName ( $appsInManifest.VisualElements.DisplayName )
} catch {
Write-Host $Error[0]
}
if (Test-Path($($desinationIconPath + "\" + $appsInManifest.VisualElements.DisplayName + ".ico")) ) {
Write-Host $("Icon successfully created: " + $desinationIconPath + "\" + $appsInManifest.VisualElements.DisplayName + ".ico")
} else {
Write-Host $("Icon NOT created: " + $desinationIconPath + "\" + $appsInManifest.VisualElements.DisplayName + ".ico")
}
}