This repository has been archived by the owner on Aug 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSilentInstall_Utilities.ps1
1701 lines (1463 loc) · 66.7 KB
/
SilentInstall_Utilities.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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#######################################################################################################################
# SilentInstall_Utilities.ps1
#
# Attributions:
# Original code from TMurgent Technologies, LLP
# New_Shortcut portion was adapted from https://gallery.technet.microsoft.com/scriptcenter/New-Shortcut-4d6fb3d8
#
# This powershell module consists of a set of functions that are useful as part of a "Silent Installation" framework.
#
#
# To use:
# Import-Module {pathto\}SilentInstall_Utilities.ps1
# Call SilentInstall_EnsureElevated
# (Optional) Call Set_PSWinSize
# (Optional) Call Set_PSWinColors
# Update variables listed in the Declarations section below
# (optional) Call SilentInstall_EnableMSIDebugging
# Call SilentInstall_PrimaryInstallations
# Perform additional customizations supported by this module, including but not limited to
# (optional) Move_Key
# (optional) New_Shortcut
# (optional) SilentInstall_FixShortcutToCmdBat
# (optional) SilentInstall_SaveLogFile
# (optional) Call SilentInstall_FlushNGensQueues
#######################################################################################################################
#--------------------------------------------------------------------------------------------------
# Declarations
# To simplify the use of this module, it declares a set of variables here that will be
# modified by the caller prior to calling the SilentInstall_PrimaryInstallations function.
# If left null or empty, the actions associated with this item will be skipped.
$Installers_x64Hash = new-object System.Collections.Specialized.OrderedDictionary
$Installers_x86Hash = new-object System.Collections.Specialized.OrderedDictionary
$CopyFiles_x64Hash = new-object System.Collections.Specialized.OrderedDictionary
$CopyFiles_x86Hash = new-object System.Collections.Specialized.OrderedDictionary
[string[]] $DesktopShortcutsToRemove = ""
[string[]] $StartMenuShortcutsToRemove = ""
[string[]] $StartMenuFoldersToRemove = ""
[string[]] $FilesToRemove_x64 = ""
[string[]] $FilesToRemove_x86 = ""
[string[]] $EnvsToRemove_x64 = ""
[string[]] $EnvsToRemove_x86 = ""
[string[]] $ServicesToDisable_x64 = ""
[string[]] $ServicesToDisable_x86 = ""
$InstallerLogFolder = "c:\Users\Public\Documents\SequencedPackage"
$InstallerLogFile = "logfile.log"
#--------------------------------------------------------------------------------------------------
#######################################################################################################################
<#
.SYNOPSIS
SilentInstall_PrimaryInstallations
erforms primary installations specified by pre-established variables and located files.
.Description
Utility to perform the primary installation activity.
This includes:
Installers hashes (from variables)
CopyFile hashes (from variables)
Reg files discovered the primary install folder
Application_Capabilies scripts discovered in the primary install folder
AppPathFixes scripts discovered in the primary install folder
ShortcutFixes scripts discovered in the primary install folder
Shortcut removals (from variables)
File Removals (from variables)
Environment Variable Removals (from variables)
Disable Services
NGen scripts discovered in the primary install folder.
.PARAMETER
None
.EXAMPLE
SilentInstall_PrimaryInstallations
#>
Function SilentInstall_PrimaryInstallations
{
[CmdletBinding()]
param()
Process {
#---------------------------------------------------------------
# Make sure folder for log file is present
if (!(Test-Path -Path $InstallerLogFolder))
{
New-Item -ItemType Directory -Path $InstallerLogFolder
}
#---------------------------------------------------------------
#---------------------------------------------------------------
# Run Installers
Run_Installers $Installers_x86Hash $Installers_x64Hash
#---------------------------------------------------------------
#---------------------------------------------------------------
# Run CopyFiles
Run_CopyFiles $CopyFiles_x86Hash $CopyFiles_x64Hash
#---------------------------------------------------------------
#--------------------------------------------------------------
# Run located reg files (if any)
Run_RegFiles $executingScriptDirectory
#---------------------------------------------------------------
#--------------------------------------------------------------
# Run located Generate_AppCapabilities files (if any, should be replaced by Apply_AutomatedFixups)
Run_AppCapabilitiesFiles $executingScriptDirectory
#---------------------------------------------------------------
#--------------------------------------------------------------
# Run located Generate_AppPathFixes files (if any, should be replaced by Apply_AutomatedFixups)
Run_AppPathFixesFiles $executingScriptDirectory
#---------------------------------------------------------------
#--------------------------------------------------------------
# Run located Generate_ShortcutFixes files (if any, should be replaced by Apply_AutomatedFixups)
Run_ShortcutFixesFiles $executingScriptDirectory
#---------------------------------------------------------------
#---------------------------------------------------------------
# Things like Remove Desktop & StartMenu Shortcuts, and Folders
LogMe_AndDisplay "Removing Shortcuts Links" $InstallerLogFile
foreach ($DesktopShortcutToRemove in $DesktopShortcutsToRemove)
{
Remove_DesktopShortcut $DesktopShortcutToRemove
}
foreach ($StartMenuShortcutToRemove in $StartMenuShortcutsToRemove)
{
Remove_StartMenuShortcut $StartMenuShortcutToRemove
}
foreach ($StartMenuFolderToRemove in $StartMenuFoldersToRemove)
{
Remove_StartMenuFolder $StartMenuFolderToRemove
}
LogMe_AndDisplay "Removing Shortcuts Links Completed" $InstallerLogFile
#-------------------------------------------------------------
#-------------------------------------------------------------
# Remove listed files
Run_RemoveFiles $FilesToRemove_x64 $FilesToRemove_x86
#------------------------------------------------------------
#-------------------------------------------------------------
# Remove listed Environment Variables
Run_RemoveEnvs $EnvsToRemove_x64 $EnvsToRemove_x86
#------------------------------------------------------------
#-------------------------------------------------------------
# Disable listed Services
Run_DisableServices $ServicesToDisable_x64 $ServicesToDisable_x86
#------------------------------------------------------------
#------------------------------------------------------------
# Run located AutomatedFixes scripts (if any)
Run_PostInstallAutomatedFixesScripts $executingScriptDirectory
#------------------------------------------------------------
#------------------------------------------------------------
# Run located rngen scripts (if any, should be replaced by Apply_AutomatedFixups)
Run_PostInstallNGenScripts $executingScriptDirectory
#------------------------------------------------------------
}
}
#######################################################################################################################
<#
.SYNOPSIS
SilentInstall_EnsureElevated
Checks to see if the script is running elevated, and if not restarts the script requesting the elevation.
.DESCRIPTION
SilentInstall-EnsureElevated is used to make sure that the script was called in an elevated powershell window.
If not, it will restart the script using "runas" with the administrator account.
This will result in a UAC prompt. But it is faster to right click on a PS1 script and run it this way.
The original call does not return if elevation is needed as that copy of the script is terminated.
.PARAMETER OriginalCmdline
String containing the original command line and arguments, to be run if elevation is needed.
Mandatory string
.PARAMETER SleepSeconds
String containing the number of seconds to keep the old window open if elevation is needed.
Optional string that defaults to 60
.EXAMPLE
SilentInstall_EnsureElevated $PSCommandPath
#>
Function SilentInstall_EnsureElevated
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, Position=0)]
[string]$OriginalCmdline,
[Parameter(Mandatory=$False, Position=1)]
[string]$SleepSeconds = 60
)
Process {
# Find PowerShell
##$psexeX86 = Get_PowerShellx86Path
$psexeNative = Get_PowerShellNativePath
# Ensure we are running as an admin, if not relaunch
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent() )
if (!$currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ))
{
# User is not an admin and does not have rights to install, so let's elevate (there will be a prompt).
(get-host).UI.RawUI.Backgroundcolor="LightGray"
clear-host
write-host -ForegroundColor DarkYellow "Notice: Relaunching because PowerShell is NOT running as an Administrator (elevated)."
Start-Process $psexeNative "-NoProfile -ExecutionPolicy Bypass -File `"$OriginalCmdline`"" -Verb RunAs;
Start-Sleep $SleepSeconds;
exit
}
}
}
#######################################################################################################################
<#
.SYNOPSIS
SilentInstall_EnableMSIDebugging
Turns on MSI debugging
.DESCRIPTION
Sets registry to ensure that both 32-bit and 64-bit MSI installers will log.
Msiexec will log the activity to files in the user's temp folder by default.
By default, all logging is enabled, otherwise you can specify the logging that you want.
See http://support.microsoft.com/en-us/help/223300/how-to-enable-windows-installer-logging for details on logging
specification.
MSI Debugging may be needed if you installing using MSI based installers and are having issues with the silent
installation and need to debug the issue.
.PARAMETER LogVals
String configuring logging details. When not specified it defaults to all known details ("voicewarmupx")
Optional string.
.EXAMPLE
SilentInstall_EnableMSIDebugging 'voicewarmupx'
#>
Function SilentInstall_EnableMSIDebugging
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, Position=0)]
[string]$LogVals ="voicewarmupx"
)
Process {
Make_KeyIfNotPresent "HKLM" "Software\Policies\Microsoft\Windows\Installer"
Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\Installer" -Name "Logging" -Value $LogVals
Make_KeyIfNotPresent "HKLM" "Software\Wow6432Node\Policies\Microsoft\Windows\Installer"
Set-ItemProperty -Path "HKLM:\Software\Wow6432Node\Policies\Microsoft\Windows\Installer" -Name "Logging" -Value $LogVals
}
}
#######################################################################################################################
<#
.SYNOPSIS
SilentInstall_SaveLogFile
Copies output from a saved log file into the pre-established utility log file.
.Description
The utilities establish a central log file, however the caller may run independent commands
and pipe the output to independent log files. This function may be called to concatenate that
log information into the central log.
This function is also used internally by the utilities.
.PARAMETER logfile2save
String path to log file to be concatenated into the central log file.
mandaroty string
.EXAMPLE
Start-Process -FilePath msiexec -ArgumentList /i, """$installer""", $InstallerFileHash.Value -Wait -RedirectStandardError redir_error.log -RedirectStandardOutput redir_out.log
SilentInstall_SaveLogFile redir_error.log
SilentInstall_SaveLogFile redir_out.log
#>
Function SilentInstall_SaveLogFile
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, Position=0)]
[string]$logfile2save
)
Process {
$logheader = "------->INSTALLER LOG: "+$logfile2save
LogMe_AndDisplay $logheader $InstallerLogFile
if (Test-Path $logfile2save)
{
$l1 = Get-Content $logfile2save
LogMe_AndDisplay $l1 $InstallerLogFile
}
else
{
LogMe_AndDisplay "No such file(s) present. " $InstallerLogFile
}
LogMe_AndDisplay "<-------INSTALLER LOG " $InstallerLogFile
}
}
#######################################################################################################################
<#
.SYNOPSIS
SilentInstall_FlushNGensQueues
Function to flush the various ngen queues.
.DESCRIPTION
Many installers of .NET apps set up to perform .net compilation optimization in the background in an ngen queue.
This function will force completion so that you have it in your package.
NOTE: You should also ensure that this has been done to your base image before the snapshot so that you don't pick
up other stuff.
.PARAMETER
None
.EXAMPLE
SilentInstall_FlushNGensQueues
#>
Function SilentInstall_FlushNGensQueues
{
[CmdletBinding()]
param()
Process {
Flush_NGensQueues $InstallerLogFile
}
}
#######################################################################################################################
<#
.SYNOPSIS
Move_Key
This script is used to move a registry key between hives (e.g: HKLM to HKCU)
.PARAMETER FromHive
Registry Hive to move from. Example 'HKLM'
.PARAMETER ParentKey
String for the full name of the parent key without hive
.PARAMETER RelativeKey
String for the relative name of the key
.PARAMETER ToHive
Registry Hive to move to. Example 'HKCU'
.INPUTS
None
.OUTPUTS
None
.EXAMPLE
Move_Key 'HKLM' 'Software\Wow6432Node\Microsoft\Internet Explorer\Extensions' '{29e5421f-6f05-4a76-938f-d7e5884f23d8}' 'HKCU'
#>
Function Move_Key
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, Position=0)]
[string]$FromHive,
[Parameter(Mandatory=$True, Position=1)]
[string]$ParentKey,
[Parameter(Mandatory=$True, Position=2)]
[string]$RelativeKey,
[Parameter(Mandatory=$True, Position=3)]
[string]$ToHive
)
Process {
LogMe_AndDisplay "Move_Key: $FromHive $ParentKey $RelativeKey $ToHive" $InstallerLogFile
if (!($FromHive -eq 'HKLM' -or $FromHive -eq 'HKCU' ))
{
LogMe_AndDisplay "$FromHive is not a valid registry hive designation." $InstallerLogFile
return
}
if (!($ToHive -eq 'HKLM' -or $ToHive -eq 'HKCU'))
{
LogMe_AndDisplay "$ToHive is not a valid registry hive designation." $InstallerLogFile
return
}
if ($ParentKey.Length -eq 0 -or $RelativeKey.Length -eq 0)
{
LogMe_AndDisplay "Parameters -ParentKey or -RelativeKey may not be empty or null." $InstallerLogFil
return
}
if ($ParentKey.StartsWith('\')) { $useParKey = $ParentKey }
else { $useParKey = "\$ParentKey" }
if (!($ParentKey.EndsWith('\'))) { $useFullKey = $useParKey+'\' }
$useFullKey = $useFullkey + $RelativeKey
$FullFrom = "$FromHive"+':'+$UseFullKey
$FullTo = "$ToHive"+':'+$UseParKey
#LogMe_AndDisplay "FullFrom = $FullFrom" $InstallerLogFile
#LogMe_AndDisplay "FullTo = $FullTo" $InstallerLogFile
if ( !(Test-Path "$FullTo" ))
{
New-Item -Path "$FullTo" -Force
}
Copy-Item -Path "$FullFrom" -Destination "$FullTo" -Recurse
Remove-Item -Path "$FullFrom" -Recurse
#LogMe_AndDisplay "done moving the key" $InstallerLogFile
}
}
#######################################################################################################################
<#
.SYNOPSIS
This script is used to create a shortcut.
.DESCRIPTION
This script uses a Com Object to create a shortcut.
.PARAMETER Path
The path to the shortcut file. .lnk will be appended if not specified. If the folder name doesn't exist, it will
be created.
.PARAMETER TargetPath
Full path of the target executable or file.
.PARAMETER Arguments
Arguments for the executable or file.
.PARAMETER Description
Description of the shortcut.
.PARAMETER HotKey
Hotkey combination for the shortcut. Valid values are SHIFT+F7, ALT+CTRL+9, etc. An invalid entry will cause the
function to fail.
.PARAMETER WorkDir
Working directory of the application. An invalid directory can be specified, but invoking the application from the
shortcut could fail.
.PARAMETER WindowStyle
Windows style of the application, Normal (1), Maximized (3), or Minimized (7). Invalid entries will result in Normal
behavior.
.PARAMETER Icon
Full path of the icon file. Executables, DLLs, etc with multiple icons need the number of the icon to be specified,
otherwise the first icon will be used, i.e.: c:\windows\system32\shell32.dll,99
.PARAMETER admin
Used to create a shortcut that prompts for admin credentials when invoked, equivalent to specifying runas.
.NOTES
Author : Rhys Edwards
Email : powershell@nolimit.to
.INPUTS
Strings and Integer
.OUTPUTS
True or False, and a shortcut
.LINK
Adapted from https://gallery.technet.microsoft.com/scriptcenter/New-Shortcut-4d6fb3d8
.EXAMPLE
New_Shortcut -Path c:\temp\notepad.lnk -TargetPath c:\windows\notepad.exe
Creates a simple shortcut to Notepad at c:\temp\notepad.lnk
.EXAMPLE
New_Shortcut "$($env:Public)\Desktop\Notepad" c:\windows\notepad.exe -WindowStyle 3 -admin
Creates a shortcut named Notepad.lnk on the Public desktop to notepad.exe that launches maximized after prompting for
admin credentials.
.EXAMPLE
New_Shortcut "$($env:USERPROFILE)\Desktop\Notepad.lnk" c:\windows\notepad.exe -icon "c:\windows\system32\shell32.dll,99"
Creates a shortcut named Notepad.lnk on the user`s desktop to notepad.exe that has a pointy finger icon (on Windows 7).
.EXAMPLE
New_Shortcut "$($env:USERPROFILE)\Desktop\Notepad.lnk" c:\windows\notepad.exe C:\instructions.txt
Creates a shortcut named Notepad.lnk on the user`s desktop to notepad.exe that opens C:\instructions.txt
.EXAMPLE
New_Shortcut "$($env:USERPROFILE)\Desktop\ADUC" %SystemRoot%\system32\dsa.msc -admin
Creates a shortcut named ADUC.lnk on the user`s desktop to Active Directory Users and Computers that launches after
prompting for admin credentials
#>
Function New_Shortcut
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True,Position=0)]
[Alias("File","Shortcut")]
[string]$Path,
[Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True,Position=1)]
[Alias("Target")]
[string]$TargetPath,
[Parameter(ValueFromPipelineByPropertyName=$True,Position=2)]
[Alias("Args","Argument")]
[string]$Arguments,
[Parameter(ValueFromPipelineByPropertyName=$True,Position=3)]
[Alias("Desc")]
[string]$Description,
[Parameter(ValueFromPipelineByPropertyName=$True,Position=4)]
[string]$HotKey,
[Parameter(ValueFromPipelineByPropertyName=$True,Position=5)]
[Alias("WorkingDirectory","WorkingDir")]
[string]$WorkDir,
[Parameter(ValueFromPipelineByPropertyName=$True,Position=6)]
[int]$WindowStyle,
[Parameter(ValueFromPipelineByPropertyName=$True,Position=7)]
[string]$Icon,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[switch]$admin
)
Process
{
If (!($Path -match "^.*(\.lnk)$"))
{
$Path = "$Path`.lnk"
}
[System.IO.FileInfo]$Path = $Path
Try
{
If (!(Test-Path $Path.DirectoryName))
{
mkdir $Path.DirectoryName -ErrorAction Stop | Out-Null
}
}
Catch
{
Write-Verbose "Unable to create $($Path.DirectoryName), shortcut cannot be created"
Return $false
Break
}
# Define Shortcut Properties
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($Path.FullName)
$Shortcut.TargetPath = $TargetPath
$Shortcut.Arguments = $Arguments
$Shortcut.Description = $Description
$Shortcut.HotKey = $HotKey
$Shortcut.WorkingDirectory = $WorkDir
$Shortcut.WindowStyle = $WindowStyle
If ($Icon)
{
$Shortcut.IconLocation = $Icon
}
Try
{
# Create Shortcut
$Shortcut.Save()
# Set Shortcut to Run Elevated
If ($admin)
{
$TempFileName = [IO.Path]::GetRandomFileName()
$TempFile = [IO.FileInfo][IO.Path]::Combine($Path.Directory, $TempFileName)
$Writer = New-Object System.IO.FileStream $TempFile, ([System.IO.FileMode]::Create)
$Reader = $Path.OpenRead()
While ($Reader.Position -lt $Reader.Length)
{
$Byte = $Reader.ReadByte()
If ($Reader.Position -eq 22)
{
$Byte = 34
}
$Writer.WriteByte($Byte)
}
$Reader.Close()
$Writer.Close()
$Path.Delete()
Rename-Item -Path $TempFile -NewName $Path.Name | Out-Null
}
Return $True
}
Catch
{
Write-Verbose "Unable to create $($Path.FullName)"
Write-Verbose $Error[0].Exception.Message
Return $False
}
}
}
#######################################################################################################################
<#
.SYNOPSIS
SilentInstall_FixShortcutToCmdBat
Modified a .lnk file with target of Bat or CMD to point to cmd.exe with /c to file.
.DESCRIPTION
Some instllers add shortcuts to BAT or CMD files, and these don't work in App-V. This function will
modify the shortcut to call cmd.exe /c BatOrCmdFile and any additional arguments (normally none).
.PARAMETER LinkPath
The fully qualified path to the .lnk file to adjust.
.PARAMETER InstallerLogFile
Full path to a log file to generate/append to.
#>
function SilentInstall_FixShortcutToCmdBat {
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, Position=0)]
[string] $LinkPath = $null,
[Parameter(Mandatory=$True, Position=1)]
[string]$InstallerLogFile
)
Process
{
LogMe_AndDisplay "Editing Shortcut: $LinkPath" $InstallerLogFile
$obj = New-Object -ComObject WScript.Shell
$link = $obj.CreateShortcut($LinkPath)
if ($link)
{
$tmp = "Oringial Shortcut found with target " + $link.TargetPath + " and Arguments " + $link.Arguments
LogMe_AndDisplay "$tmp" $InstallerLogFile
$wdir = ($link.TargetPath).Replace("\"+(Split-Path ($link.TargetPath) -Leaf),"")
$link.Arguments = "-c '" + $link.TargetPath + "' " + $link.Arguments
$link.TargetPath = 'C:\Windows\System32\cmd.exe'
$link.WorkingDirectory = $wdir
$link.Save()
$tmp = "Saved new shortcut with target " + $link.TargetPath + " and Arguments " + $link.Arguments
LogMe_AndDisplay "$tmp" $InstallerLogFile
}
else
{
LogMe_AndDisplay "Failed to find shortcut file." $InstallerLogFile
}
}
}
#######################################################################################################################
<#
.SYNOPSIS
Funtion to sets the powershell window size and optionaly position
.DESCRIPTION
This utility may be used to set the size and position of the powershell window.
.PARAMETER MaxWidth
Mandatory int
Width of the window, in columns.
.PARAMETER MaxHeight
Mandatory int
Height of the window, in rows.
.PARAMETER PosX
Optional int
Left position on the screen in pixels, if both PosX and PosY are specified.
.PARAMETER PosY
Optional int
Top position on the screen in picels, if both PosX and PosY are specified.
#>
Function Set_PSWinSize
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, Position=0)]
[int]$MaxWidth,
[Parameter(Mandatory=$True, Position=1)]
[int]$MaxHeight,
[Parameter(Mandatory=$False, Position=2)]
[int]$PosX = (0),
[Parameter(Mandatory=$False, Position=3)]
[int]$PosY = (0)
)
Process
{
if ($Host.Name -match "console")
{
$MyWindowSize = $Host.UI.RawUI.WindowSize
$MyWindowSize.Height = ($MaxHeight)
$MyWindowSize.Width = ($Maxwidth)
$host.UI.RawUI.set_windowSize($MyWindowSize)
if ($PosX -gt 0 -and $PosY -gt 0)
{
$MyWindowPos = $Host.UI.RawUI.WindowPosition
$MyWindowPos.X = ($PosX)
$MyWindowPos.Y = ($PosY)
$host.UI.RawUI.set_windowPosition($MyWindowPos)
}
}
}
}
#######################################################################################################################
<#
.SYNOPSIS
Set_PSWinColors
A function to set powershell colors and window title
.DESCRIPTION
This function sets the background and foreground color of the current powershell window. It also sets the window
title, and clears the screen.
The requested window title in enhanced with the following infomration:
Elevation
Username
DateStamp
.PARAMETER Background
Mandatory string Parameter
Color for the background of the powershell window.
.PARAMETER Foreground
Mandatory string Parameter
Color for text in the powershell window.
.PARAMETER WinTitle
Mandatory string Parameter
Title string for the window. This will be "enhanced".
.PARAMETER Elevated
Mandatory bool Parameter
Indicates if the window is elevated. This will be indicated in the enhanced title.
.EXAMPLE
Set_PSWinColors 'Black' 'White' "My purpose" $True
#>
function Set_PSWinColors
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, Position=0)]
[string]$Background,
[Parameter(Mandatory=$True, Position=1)]
[string]$Foreground,
[Parameter(Mandatory=$True, Position=2)]
[string]$WinTitle,
[Parameter(Mandatory=$True, Position=3)]
[bool]$Elevated
)
Process
{
$host.ui.RawUI.BackgroundColor = $Background
$host.ui.RawUI.ForegroundColor = $Foreground
Clear-Host
If ($Elevated)
{
$Elevatedstr = "[Elevated]"
}
else
{
$Elevatedstr = ""
}
$Title = $Elevatedstr + " $ENV:USERNAME".ToUpper() + ": $($Host.Name) " + " - " + (Get-Date).toshortdatestring() + $WinTitle
$Host.UI.RawUI.set_WindowTitle($Title)
}
}
#------------ The remaining functions are intended for internal consumption only --------------------------------------
###################################################################################################
# Function to run the installers list (OrderedDictionary) as appropriate for the bitness of the OS
#
# The OrderedDictionaries have entries as follows:
# Hash Name: Path to Installer
# Hash Value: Paramaters
#
# Several types of installers are understood:
# .ZIP: The zip file is extracted to the file folder listed in the hash value.
# .MSI: MSIEXEC is run with -I and the MSI filename with parameters.
# .MSP: MSIEXEC is run with -P and the MSP filename with parameters.
# else: The named file is run with parameters.
#
# Except for Zip, individual arguments must be seperated by commas, as in:
# /qn, INSTALLFOLDER="C:\foo"
#
# The x64 list is run on x64 OSs, the x86 on 32-bit OS.
Function Run_Installers(
[System.Collections.Specialized.OrderedDictionary] $Installers_x86Hash,
[System.Collections.Specialized.OrderedDictionary] $Installers_x64Hash)
{
LogMe_AndDisplay "Starting installations." $InstallerLogFile
$psexeNative = Get_PowerShellNativePath
$InstallerFiles_Hash = New-Object System.Collections.Specialized.OrderedDictionary
if ([Environment]::Is64BitOperatingSystem -eq $true )
{
$InstallerFiles_Hash = $Installers_x64Hash
}
else
{
$InstallerFiles_Hash = $Installers_x86Hash
}
foreach ($InstallerFileHash in $InstallerFiles_Hash.GetEnumerator())
{
$tmpNoWait = $false
if ($InstallerFileHash.Key.Contains(':\'))
{
$installer = $InstallerFileHash.Key
if ($installer.StartsWith('-'))
{
#Used to solve issue with Paint.Net installer that rolls back using the normal method for an unknown reason.
$installer = $installer.Substring(1)
$tmpNoWait = $true;
}
}
else
{
$installer = $executingScriptDirectory + '\' + $InstallerFileHash.Key
if ($InstallerFileHash.Key.StartsWith('-'))
{
#Used to solve issue with Paint.Net installer that rolls back using the normal method for an unknown reason.
$installer =$executingScriptDirectory + '\' + $InstallerFileHash.Key.Substring(1)
$tmpNoWait = $true;
}
}
if ($installer.ToLower().EndsWith(".msi"))
{
$log = ' running process -FilePath msiexec -ArgumentList /i, '+$installer+', '+$InstallerFileHash.Value+' -Wait'
LogMe_AndDisplay $log $InstallerLogFile
Start-Process -FilePath msiexec -ArgumentList /i, """$installer""", $InstallerFileHash.Value -Wait -RedirectStandardError redir_error.log -RedirectStandardOutput redir_out.log
ProcessLogMe_AndDisplay 'redir_error.log' 'redir_out.log' $InstallerLogFile
}
elseif ($installer.ToLower().EndsWith(".msp"))
{
$log = ' running process -FilePath msiexec -ArgumentList /update, '+$installer+', '+$InstallerFileHash.Value+' -Wait'
LogMe_AndDisplay $log $InstallerLogFile
Start-Process -FilePath msiexec -ArgumentList /update, """$installer""", $InstallerFileHash.Value -Wait -RedirectStandardError redir_error.log -RedirectStandardOutput redir_out.log
ProcessLogMe_AndDisplay 'redir_error.log' 'redir_out.log' $InstallerLogFile
}
elseif ($installer.ToLower().EndsWith(".zip"))
{
$log = ' extracting files from '+$installer+' to '+$InstallerFileHash.Value
LogMe_AndDisplay $log $InstallerLogFile
Add-Type -AssemblyName "system.io.compression.filesystem"
[io.compression.zipfile]::ExtractToDirectory($installer,$InstallerFileHash.Value)
}
elseif ($installer.ToLower().EndsWith(".ps1"))
{
$log = ' running process -FilePath ' +$psexeNative+ ' -ArgumentList -NoProfile, -ExecutionPolicy, Bypass, -File '+$installer+', '+$InstallerFileHash.Value+' -Wait'
LogMe_AndDisplay $log $InstallerLogFile
Start-Process -Wait -FilePath "$psexeNative" -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", """$installer""", $InstallerFileHash.Value -RedirectStandardError redir_error.log -RedirectStandardOutput redir_out.log
ProcessLogMe_AndDisplay 'redir_error.log' 'redir_out.log' $InstallerLogFile
}
else
{
if ($tmpNoWait)
{
#Used to solve issue with Paint.Net installer that rolls back using the normal method for an unknown reason.
$xx = '/c '+$installer+' '+$InstallerFileHash.Value
$log = ' running c:\windows\system32\cmd.exe ' + $xx
LogMe_AndDisplay $log $InstallerLogFile
c:\windows\system32\cmd.exe $xx
Start-Sleep 90
}
else
{
$log = ' running process -FilePath '+"""$installer"""+' -ArgumentList '+$InstallerFileHash.Value+' -Wait'
LogMe_AndDisplay $log $InstallerLogFile
Start-Process -FilePath """$installer""" -ArgumentList $InstallerFileHash.Value -Wait -RedirectStandardError redir_error.log -RedirectStandardOutput redir_out.log -LoadUserProfile
ProcessLogMe_AndDisplay 'redir_error.log' 'redir_out.log' $InstallerLogFile $false $true
}
}
}
LogMe_AndDisplay "Installations Completed." $InstallerLogFile
}
###################################################################################################
# Function to copy files from the copy list
#
# The OrderedDictionaries have entries as follows:
# Hash Name: Path to source file
# Hash Value: Path to destination folder
#
# The x64 list is processed on x64 OSs, the x86 on 32-bit OS.
function Run_CopyFiles(
[System.Collections.Specialized.OrderedDictionary] $CopyFiles_x86Hash,
[System.Collections.Specialized.OrderedDictionary] $CopyFiles_x64Hash)
{
LogMe_AndDisplay "Starting CopyFiles." $InstallerLogFile
$CopyFiles_Hash = New-Object System.Collections.Specialized.OrderedDictionary
if ([Environment]::Is64BitOperatingSystem -eq $true )
{
$CopyFiles_Hash = $CopyFiles_x64Hash
}
else
{
$CopyFiles_Hash = $CopyFiles_x86Hash
}
foreach ($CopyFileHash in $CopyFiles_Hash.GetEnumerator())
{
$log = 'Adding '+$CopyFileHash.Key+' to folder '+$CopyFileHash.Value
LogMe_AndDisplay $log $InstallerLogFile
if (!(Test-Path $CopyFileHash.Value))
{
$err1 = new-item -ItemType Directory -Force $CopyFileHash.Value
$serr1 = "Create Directory "+$CopyFileHash.Value+": "+$err1
LogMe_AndDisplay $serr1 $InstallerLogFile
}
$err = Copy-Item $CopyFileHash.Key -Destination $CopyFileHash.Value *>&1
$serr = "Copy file result: "+$err
LogMe_AndDisplay $serr $InstallerLogFile
}
LogMe_AndDisplay "CopyFiles Completed." $InstallerLogFile
}
###################################################################################################
# Function to find/run reg imports
# This will find all .reg files in the given folder
# Those whose base names end in x86 or x64 will only be run on the same bitness as the OS,
# All others will just be run.
# No control over the order of running is provided.
function Run_RegFiles([string]$executingScriptDirectory)
{
LogMe_AndDisplay "Starting any registration imports." $InstallerLogFile
$cnt = 0
#---------------------------------------------------------------
#Look for a .reg file to import
Get-ChildItem $executingScriptDirectory | Where-Object { $_.Extension -eq '.reg' } | ForEach-Object {
if ($_.FullName -like "*x64.reg")
{
if ([Environment]::Is64BitOperatingSystem -eq $true)
{
$log = ' importing for x64 '+ $_.FullName
LogMe_AndDisplay $log $InstallerLogFile
reg import $_.FullName
$cnt = $cnt + 1
}
}
elseif ($_.FullName -like "*x86.reg")
{
if ([Environment]::Is64BitOperatingSystem -eq $false)
{
$log = ' importing for x86 '+ $_.FullName
LogMe_AndDisplay $log $InstallerLogFile
reg import $_.FullName
$cnt = $cnt + 1
}
}
else
{
$log = ' importing '+$_.FullName
LogMe_AndDisplay $log $InstallerLogFile