-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRfaPowerShell.psm1
More file actions
1048 lines (860 loc) · 38.2 KB
/
Copy pathRfaPowerShell.psm1
File metadata and controls
1048 lines (860 loc) · 38.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
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
# v1.1.3.12
# Load some external functions
$web = New-Object Net.WebClient
$TheseFunctionsForPstFileInfo = @(
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Get-DsRegCmdStatus.ps1'
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Get-CimLocalDisk.ps1'
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Find-FileByExtension.ps1'
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Format-ObjectToString.ps1'
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Find-PstFullName.ps1'
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Confirm-RequiresAdmin.ps1'
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Get-MdmHardwareId.ps1'
'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Get-InstalledSoftware.ps1'
)
Foreach ($uri in $TheseFunctionsForPstFileInfo) {
$web.DownloadString($uri) | Invoke-Expression
}
$web.Dispose | Out-Null
function Add-TrueTypeFont {
<#
.SYNOPSIS
Adds TTF files to Windows.
.DESCRIPTION
Adds TTF files to Windows Control Panel on the local computer only. Must run as admin.
.EXAMPLE
dir \\server\share\fonts\*.ttf | Add-TrueTypeFont
.NOTES
Depreciated. No not use. Use Install-Font instead.
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidatePattern('.+\.ttf$')]
[Alias('FilePath','FullName')]
[string[]]
$Path
)
begin {
# Namespace ID
$FONTS = 0x14
Set-Variable -Name ErrorActionPreference -Scope Script -Value 'Stop'
Try {
$objShell = New-Object -ComObject Shell.Application
} Catch {
throw "Missing COMObject: Shell.Application"
}
Try {
$objFolder = $objShell.Namespace($FONTS)
} Catch {
throw "Unable to load Font Namespace:`n$($_.Exception.Message)"
}
Set-Variable -Name ErrorActionPreference -Scope Script -Value 'SilentlyContinue'
}
process {
Foreach ($p in $Path) {
$objFile = Get-Item $p
$FontName = $objFile.name
if (Test-Path "c:\windows\fonts\$FontName") {
Write-Verbose "Font already installed: $($FontName)"
} else {
if (Test-Path $objFile.FullName) {
$CopyOptions = 4 + 16; # from https://www.reddit.com/r/sysadmin/comments/a64lax/windows_1809_breaks_powershell_script_to_install/ebs68wj?utm_source=share&utm_medium=web2x
[void]($ObjFolder.CopyHere($objFile.fullname, $CopyOptions));
$regPath = "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Fonts"
New-ItemProperty -Name $objFile.fullname -Path $regPath -PropertyType string -Value ($objFile.fullname)
# Test each action
$Installed = Get-Font $FontName
if ($Installed) {
Write-Verbose "Font successfully installed: $($FontName)"
} else {
Write-Warning "Font not installed: $($FontName)!"
}
} else {
Write-Warning "Path not found: $($objFile.fullname)"
}
}
}
}
end {
if ($Error) {
$Error | ForEach-Object { Write-Verbose $_.Exception.Message }
}
}
}
function Install-Font {
<#
.SYNOPSIS Install system fonts for all users
.PARAMETER FontPath Provide path to a font or a folder containing fonts
.PARAMETER Recurse Scan subdirectories
.EXAMPLE - Install Fonts from folder
Install-Font "C:\Temp\Helvetica Neue"
.EXAMPLE - Install one font
Install-Font "C:\Temp\Helvetica Neue\HelveticaNeueLTStd-HvIt.otf"
.NOTES
Borrowed from: https://www.joseespitia.com/2019/10/07/install-font-function/
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String]$FontPath
)
if(Test-Path $FontPath) {
$FontFile = Get-Item -Path $FontPath
if ($FontFile -is [IO.FileInfo]) {
if ($FontFile.Extension -notin ('.fon','.otf','.ttc','.ttf')) {
Throw ("The file provided does not appear to be a valid font")
}
} else {
Throw ("Expected font or folder")
}
} else {
Throw [System.IO.FileNotFoundException]::New("Could not find path: $FontPath")
}
foreach ($Font in $FontFile) {
$FontName = $Font.Basename
Write-Verbose "Installing font: $FontName"
Copy-Item $Font "C:\Windows\Fonts" -Force
[void] (New-ItemProperty -Name $FontName -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Fonts" -PropertyType String -Value $Font.Name -Force)
}
}#END function Install-Font
function Get-PathFolders
{
$env:Path -split ';' |
foreach -Process {
if ( -not [string]::IsNullOrEmpty($_) ) {
$_.trimend('\\')
}
}
}
function Receive-PsExec
{
[CmdletBinding()]
Param
(
# Where to grab the file from
[string]
$SourceUri = 'https://automate.rfa.com/rfadl/PsExec.exe',
# Where to download the file to
[string]
$TargetDir = $env:windir,
# Force overwite existing file
[switch]$Force
)
Begin
{
$WebClient = new-object System.Net.WebClient
$Paths = Get-PathFolders
$FoundHere = @()
$Paths | foreach -Process {
if (
Test-Path (Join-Path $_ 'psexec.exe')
)
{
$FoundHere += (Join-Path $_ 'psexec.exe')
}
}
$PsExecExists = $FoundHere.Count -gt 0
}
Process {}
End
{
# Abort if found in a path location.
if( -not $PsExecExists -or $Force)
{
# Download the file into its target location
Try {
$WebClient.DownloadFile($SourceUri,$TargetDir)
} Catch {
throw "File download failed.`n$($_.Exception)"
}
# Check to see if it worked
if (Test-Path $TargetDir) {
Write-Verbose "File Downloaded OK"
} else {
Write-Warning "File Download Failed!"
}
}
}
}
function Get-RebootReport {
[CmdletBinding()]
param (
# Computer(s) to report on reboot history.
[Parameter(Position=0)]
[string[]]
$ComputerName=$env:COMPUTERNAME
)
begin {
}
process {
foreach ($Computer in $ComputerName) {
if ( ( Test-Connection $Computer -Count 1 -ea 0 ) -eq $null ){
Write-Warning "The device named $Computer is not responding to an Echo request!"
}else{
Get-WinEvent -ComputerName $Computer -FilterHashtable @{
logname='System'; id=1074} |
ForEach-Object {
$rv = New-Object PSObject |
Select-Object Date,
User,
Action,
Process,
Reason,
ReasonCode,
Comment
$rv.Date = $_.TimeCreated
$rv.User = $_.Properties[6].Value
$rv.Process = $_.Properties[0].Value -replace '^.*\\' -replace '\s.*$'
$rv.Action = $_.Properties[4].Value
$rv.Reason = $_.Properties[2].Value
$rv.ReasonCode = $_.Properties[3].Value
$rv.Comment = $_.Properties[5].Value
$rv
}
}
}
}
end {
}
}
Function Get-PendingReboot {
<#
.SYNOPSIS
Gets the pending reboot status on a local or remote computer.
.DESCRIPTION
This function will query the registry on a local or remote computer and determine if the
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations"
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.
CBServicing = Component Based Servicing (Windows 2008+)
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)
PendFileRename = PendingFileRenameOperations (Windows 2003+)
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-
Virus leverage this key for def/dat removal, giving a false positive PendingReboot
.PARAMETER ComputerName
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).
.PARAMETER ErrorLog
A single path to send error data to a log file.
.EXAMPLE
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending
-------- ----------- ------------- ------------ -------------- -------------- -------------
DC01 False False False False
DC02 False False False False
FS01 False False False False
This example will capture the contents of C:\ServerList.txt and query the pending reboot
information from the systems contained in the file and display the output in a table. The
null values are by design, since these systems do not have the SCCM 2012 client installed,
nor was the PendingFileRenameOperations value populated.
.EXAMPLE
PS C:\> Get-PendingReboot
Computer : WKS01
CBServicing : False
WindowsUpdate : True
CCMClient : False
PendComputerRename : False
PendFileRename : False
PendFileRenVal :
RebootPending : True
This example will query the local machine for pending reboot information.
.EXAMPLE
PS C:\> $Servers = Get-Content C:\Servers.txt
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation
This example will create a report that contains pending reboot information.
.LINK
Component-Based Servicing:
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx
PendingFileRename/Auto Update:
http://support.microsoft.com/kb/2723674
http://technet.microsoft.com/en-us/library/cc960241.aspx
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx
SCCM 2012/CCM_ClientSDK:
http://msdn.microsoft.com/en-us/library/jj902723.aspx
.NOTES
Author: Brian Wilhite
Email: bcwilhite (at) live.com
Date: 29AUG2012
PSVer: 2.0/3.0/4.0/5.0
Updated: 27JUL2015
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)
Added CCMClient property - Used with SCCM 2012 Clients only
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter
Removed $Data variable from the PSObject - it is not needed
Bug with the way CCMClientSDK returned null value if it was false
Removed unneeded variables
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry
Removed .Net Registry connection, replaced with WMI StdRegProv
Added ComputerPendingRename
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("CN","Computer")]
[String[]]$ComputerName="$env:COMPUTERNAME",
[String]$ErrorLog
)
Begin { }## End Begin Script Block
Process {
Foreach ($Computer in $ComputerName) {
Try {
## Setting pending values to false to cut down on the number of else statements
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false
## Setting CBSRebootPend to null since not all versions of Windows has this value
$CBSRebootPend = $null
## Querying WMI for build version
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop
## Making registry connection to the local/remote computer
$HKLM = [UInt32] "0x80000002"
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"
## If Vista/2008 & Above query the CBS Reg Key
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"
}
## Query WUAU from the registry
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"
## Query PendingFileRenameOperations from the registry
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")
$RegValuePFRO = $RegSubKeySM.sValue
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')
## Query ComputerName and ActiveComputerName from the registry
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName")
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {
$CompPendRen = $true
}
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true
If ($RegValuePFRO) {
$PendFileRename = $true
}
## Determine SCCM 2012 Client Reboot Pending Status
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0
$CCMClientSDK = $null
$CCMSplat = @{
NameSpace='ROOT\ccm\ClientSDK'
Class='CCM_ClientUtilities'
Name='DetermineIfRebootPending'
ComputerName=$Computer
ErrorAction='Stop'
}
## Try CCMClientSDK
Try {
$CCMClientSDK = Invoke-WmiMethod @CCMSplat
} Catch [System.UnauthorizedAccessException] {
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue
If ($CcmStatus.Status -ne 'Running') {
Write-Warning "$Computer`: Error - CcmExec service is not running."
$CCMClientSDK = $null
}
} Catch {
$CCMClientSDK = $null
}
If ($CCMClientSDK) {
If ($CCMClientSDK.ReturnValue -ne 0) {
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)"
}
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {
$SCCM = $true
}
}
Else {
$SCCM = $null
}
## Creating Custom PSObject and Select-Object Splat
$SelectSplat = @{
Property=(
'Computer',
'CBServicing',
'WindowsUpdate',
'CCMClientSDK',
'PendComputerRename',
'PendFileRename',
'PendFileRenVal',
'RebootPending'
)}
New-Object -TypeName PSObject -Property @{
Computer=$WMI_OS.CSName
CBServicing=$CBSRebootPend
WindowsUpdate=$WUAURebootReq
CCMClientSDK=$SCCM
PendComputerRename=$CompPendRen
PendFileRename=$PendFileRename
PendFileRenVal=$RegValuePFRO
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)
} | Select-Object @SelectSplat
} Catch {
Write-Warning "$Computer`: $_"
## If $ErrorLog, log the file to a user specified location/path
If ($ErrorLog) {
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append
}
}
}## End Foreach ($Computer in $ComputerName)
}## End Process
End { }## End End
}## End Function Get-PendingReboot
function Get-HotfixApiCombo {
param ()
$Session = New-Object -ComObject "Microsoft.Update.Session"
$Searcher = $Session.CreateUpdateSearcher()
$historyCount = $Searcher.GetTotalHistoryCount()
$UpdateHistory = $Searcher.QueryHistory(0, $historyCount)
$KBs = @()
foreach ($Update in $UpdateHistory) {
[regex]::match($Update.Title,'(KB[0-9]{6,7})').value | Where-Object {$_ -ne ""} | foreach {
$KB = New-Object -TypeName PSObject
$KB | Add-Member -MemberType NoteProperty -Name KB -Value $_
$KB | Add-Member -MemberType NoteProperty -Name Title -Value $Update.Title
$KB | Add-Member -MemberType NoteProperty -Name Description -Value $Update.Description
$KB | Add-Member -MemberType NoteProperty -Name Date -Value $Update.Date
$KBs += $KB
}
}
$result = $KBs | select date,kb
$hf = Get-Hotfix
$Result += $HF |
where {@($KBs.kb|select -Unique) -notcontains $_.hotfixID} |
select @{n='date';exp={$_.installedon}}, @{n='kb';exp={$_.hotfixid}}
$Result | sort date
}
Function Get-InstalledSoftware {
<#
.SYNOPSIS
Get-InstalledSoftware retrieves a list of installed software
.DESCRIPTION
Get-InstalledSoftware opens up the specified (remote) registry and scours it for installed software. When found it returns a list of the software and it's version.
.PARAMETER ComputerName
The computer from which you want to get a list of installed software. Defaults to the local host.
.EXAMPLE
Get-InstalledSoftware DC1
This will return a list of software from DC1. Like:
Name Version Computer UninstallCommand
---- ------- -------- ----------------
7-Zip 9.20.00.0 DC1 MsiExec.exe /I{23170F69-40C1-2702-0920-000001000000}
Google Chrome 65.119.95 DC1 MsiExec.exe /X{6B50D4E7-A873-3102-A1F9-CD5B17976208}
Opera 12.16 DC1 "C:\Program Files (x86)\Opera\Opera.exe" /uninstall
.EXAMPLE
Import-Module ActiveDirectory
Get-ADComputer -filter 'name -like "DC*"' | Get-InstalledSoftware
This will get a list of installed software on every AD computer that matches the AD filter (So all computers with names starting with DC)
.INPUTS
[string[]]Computername
.OUTPUTS
PSObject with properties: Name,Version,Computer,UninstallCommand
.NOTES
Copied by Tony Pagliaro (RFA) from: https://community.spiceworks.com/scripts/show_download/2170-get-a-list-of-installed-software-from-a-remote-computer-fast-as-lightning
Author: Anthony Howell
To add directories, add to the LMkeys (LocalMachine)
.LINK
[Microsoft.Win32.RegistryHive]
[Microsoft.Win32.RegistryKey]
#>
Param(
[Alias('Computer','ComputerName','HostName')]
[Parameter(
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$true,
Position=1
)]
[string]$Name = $env:COMPUTERNAME
)
Begin{
$lmKeys = "Software\Microsoft\Windows\CurrentVersion\Uninstall","SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
$lmReg = [Microsoft.Win32.RegistryHive]::LocalMachine
$cuKeys = "Software\Microsoft\Windows\CurrentVersion\Uninstall"
$cuReg = [Microsoft.Win32.RegistryHive]::CurrentUser
}
Process{
if (!(Test-Connection -ComputerName $Name -count 1 -quiet)) {
Write-Error -Message "Unable to contact $Name. Please verify its network connectivity and try again." -Category ObjectNotFound -TargetObject $Computer
Break
}
$masterKeys = @()
$remoteCURegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($cuReg,$computer)
$remoteLMRegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($lmReg,$computer)
foreach ($key in $lmKeys) {
$regKey = $remoteLMRegKey.OpenSubkey($key)
foreach ($subName in $regKey.GetSubkeyNames()) {
foreach($sub in $regKey.OpenSubkey($subName)) {
$masterKeys += (New-Object PSObject -Property @{
"ComputerName" = $Name
"Name" = $sub.getvalue("displayname")
"SystemComponent" = $sub.getvalue("systemcomponent")
"ParentKeyName" = $sub.getvalue("parentkeyname")
"Version" = $sub.getvalue("DisplayVersion")
"UninstallCommand" = $sub.getvalue("UninstallString")
"InstallDate" = $sub.getvalue("InstallDate")
"RegPath" = $sub.ToString()
})
}
}
}
foreach ($key in $cuKeys) {
$regKey = $remoteCURegKey.OpenSubkey($key)
if ($regKey -ne $null) {
foreach ($subName in $regKey.getsubkeynames()) {
foreach ($sub in $regKey.opensubkey($subName)) {
$masterKeys += (New-Object PSObject -Property @{
"ComputerName" = $Name
"Name" = $sub.getvalue("displayname")
"SystemComponent" = $sub.getvalue("systemcomponent")
"ParentKeyName" = $sub.getvalue("parentkeyname")
"Version" = $sub.getvalue("DisplayVersion")
"UninstallCommand" = $sub.getvalue("UninstallString")
"InstallDate" = $sub.getvalue("InstallDate")
"RegPath" = $sub.ToString()
})
}
}
}
}
$woFilter = {$null -ne $_.name -AND $_.SystemComponent -ne "1" -AND $null -eq $_.ParentKeyName}
$props = 'Name','Version','ComputerName','Installdate','UninstallCommand','RegPath'
$masterKeys = ($masterKeys | Where-Object $woFilter | Select-Object $props | Sort-Object Name)
$masterKeys
}
End{}
}
function Set-EnvironmentVariable {
<#
.SYNOPSIS
Add/update environment variable.
.DESCRIPTION
Changes the given environment variable to the given value under the given scope (user profile by default).
.EXAMPLE
Set-EnvVariable -Name 'MyVariable' -Value 'MyValue' -Scope 'Machine'
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
[Parameter(Mandatory=$true,
Position=0)]
[string]
$Name,
[Parameter(Position=1)]
[string]
$Value,
[Parameter(Position=2)]
[ValidateSet('Machine', 'User', 'Process')]
[string]
$Scope = "User"
)
if ($pscmdlet.ShouldProcess("Environment Variable '$Name' under $Scope scope", "Set value to $Value")) {
[Environment]::SetEnvironmentVariable($Name, $Value, $Scope)
Write-Verbose "Environment Variable $Name was set to '$Value' under $Scope."
}
if ($Scope -ne 'Process') {
Write-Warning "Please restart your session to use the new variable."
}
}
function Install-DotNet35 {
<#
.EXAMPLE
Install-DotNet35
.NOTES
Run this command as a local admin.
From https://raw.githubusercontent.com/LabtechConsulting/LabTech-Powershell-Module/master/LabTech.psm1
#>
$DotNET = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse -EA 0 | Get-ItemProperty -name Version,Release -EA 0 | Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} | Select-Object -ExpandProperty Version -EA 0
If (-not ($DotNet -like '3.5.*')){
Write-Output ".NET Framework 3.5 installation needed."
#Install-WindowsFeature Net-Framework-Core
$OSVersion = [System.Environment]::OSVersion.Version
If ([version]$OSVersion -gt [version]'6.2'){
Try{
If ( $PSCmdlet.ShouldProcess('NetFx3', 'Enable-WindowsOptionalFeature') ) {
$Install = Get-WindowsOptionalFeature -Online -FeatureName 'NetFx3'
If (!($Install.State -eq 'EnablePending')) {
$Install = Enable-WindowsOptionalFeature -Online -FeatureName 'NetFx3' -All -NoRestart
}
If ($Install.RestartNeeded -or $Install.State -eq 'EnablePending') {
Write-Output ".NET Framework 3.5 installed but a reboot is needed."
}
}
}
Catch{
Write-Error "ERROR: Line $(LINENUM): .NET 3.5 install failed." -ErrorAction Continue
If (!($Force)) { Write-Error ("Line $(LINENUM):",$Install) -ErrorAction Stop }
}
}
ElseIf ([version]$OSVersion -gt [version]'6.1'){
If ( $PSCmdlet.ShouldProcess("NetFx3", "Add Windows Feature") ) {
Try {$Result=& "$env:windir\system32\Dism.exe" /English /NoRestart /Online /Enable-Feature /FeatureName:NetFx3 2>''}
Catch {Write-Output "Error calling Dism.exe."; $Result=$Null}
Try {$Result=& "$env:windir\system32\Dism.exe" /English /Online /Get-FeatureInfo /FeatureName:NetFx3 2>''}
Catch {Write-Output "Error calling Dism.exe."; $Result=$Null}
If ($Result -contains 'State : Enabled'){
Write-Warning "WARNING: Line $(LINENUM): .Net Framework 3.5 has been installed and enabled."
} ElseIf ($Result -contains 'State : Enable Pending'){
Write-Warning "WARNING: Line $(LINENUM): .Net Framework 3.5 installed but a reboot is needed."
} Else {
Write-Error "ERROR: Line $(LINENUM): .NET Framework 3.5 install failed." -ErrorAction Continue
If (!($Force)) { Write-Error ("ERROR: Line $(LINENUM):",$Result) -ErrorAction Stop }
}#End If
}#End If
}#End If
$DotNET = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version -EA 0 | Where-Object{ $_.PSChildName -match '^(?!S)\p{L}'} | Select-Object -ExpandProperty Version
}#End If
If (-not ($DotNet -like '3.5.*')){
If (($Force)) {
If ($DotNet -match '(?m)^[2-4].\d'){
Write-Error "ERROR: Line $(LINENUM): .NET 3.5 is not detected and could not be installed." -ErrorAction Continue
} Else {
Write-Error "ERROR: Line $(LINENUM): .NET 2.0 or greater is not detected and could not be installed." -ErrorAction Stop
}#End If
} Else {
Write-Error "ERROR: Line $(LINENUM): .NET 3.5 is not detected and could not be installed." -ErrorAction Stop
}#End If
}#End If
}
function Get-ADSiteSubnets {
<#
.EXAMPLE
(Get-ADSiteSubnets).subnets
Name Site
---- ----
192.168.111.0/24 Default-First-Site-Name
10.1.111.0/24 Default-First-Site-Name
192.168.113.0/24 SF
192.168.213.0/24 SF
#>
[CmdletBinding()]
param ()
$Sites = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
foreach ($Site in $Sites) {
New-Object -Type PSObject -Property @{
SiteName = $site.Name
SubNets = $site.Subnets
Servers = $Site.Servers
}
}
}
function Send-WOL
{
<#
.SYNOPSIS
Send a WOL packet to a broadcast address
.PARAMETER mac
The MAC address of the device that need to wake up
.PARAMETER ip
The IP address where the WOL packet will be sent to
.EXAMPLE
Send-WOL -mac 00:11:32:21:2D:11 -ip 192.168.8.255
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,Position=1)]
[string]$mac,
[string]$ip="255.255.255.255",
[int]$port=9
)
$broadcast = [Net.IPAddress]::Parse($ip)
$mac=(($mac.replace(":","")).replace("-","")).replace(".","")
$target=0,2,4,6,8,10 | % {[convert]::ToByte($mac.substring($_,2),16)}
$packet = (,[byte]255 * 6) + ($target * 16)
$UDPclient = new-Object System.Net.Sockets.UdpClient
$UDPclient.Connect($broadcast,$port)
[void]$UDPclient.Send($packet, 102)
}
function Assert-RegValueAndRestartService {
<#
.SYNOPSIS
Update a registry value and restart services.
.DESCRIPTION
Given a Key Path, Property Name, Value, and Service Name(s),
this function will create or set the DWord value if required,
then restart the services if a change was made.
Other Property Types other than DWord are available,
please use tab-completion for the PropertyType parameter.
.PARAMETER KeyPath
Full hive/key/path
.PARAMETER PropertyName
Property name to add
.PARAMETER PropertyType
Value type for the Property (e.g. dword); please use tab-completion
.PARAMETER Value
Value for the Property
.PARAMETER ServiceName
Name(s)--NOT DisplayName--of the services to restart,
multiple OK if you put them in the correct STOP order,
it will then start them all in the reverse order from the stop order.
.EXAMPLE
$Splat = @{
KeyPath = 'HKLM:\SOFTWARE\PowerShell\Awesomeness'
PropertyName = 'DisableAwesome'
Value = 0
ServiceName = 'bits'
}
Assert-RegValueAndRestartService @Splat -Verbose
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
param (
# Full hive/key/path
[Parameter(Mandatory=$true)]
[string]
$KeyPath,
# Property name to add
[Parameter(Mandatory=$true)]
[string]
$PropertyName,
# Value type for the Property (e.g. dword); please use tab-completion
[Parameter()]
[ValidateSet('String','ExpandString','Binary',
'DWord','MultiString','Qword','Unknown')]
[string]
$PropertyType='DWord',
# Value for the Property
[Parameter(Mandatory=$true)]
$Value,
# Name(s)--NOT DisplayName--of the services to restart, multiple OK if you put them in the correct STOP order, it will then start them all in the reverse order from the stop order.
[Parameter(Mandatory=$true)]
[string[]]
$ServiceName
)
begin {
# Define the WMI call we will make several times
$WmiSplat = @{
Filter = [string]('Name = "' + $svcName + '"')
Class = 'win32_service'
ErrorAction = 0
}
# Define a boolean to enable if changes are made which will require the service(s) to restart.
$ServiceRestartRequired = $false
}
end {
# Does the path exist?
$PathFound = Get-Item $KeyPath -ea 0
if (-not $PathFound) {
# If not create the path
if ($PSCmdlet.ShouldProcess($KeyPath,'Create New Path')) {
New-Item -Path $KeyPath
$ServiceRestartRequired = $true
}
}
# Does the property exist?
$GipSplat = @{
Path = $KeyPath
Name = $PropertyName
ErrorAction = 0
}
$PropertyFound = Get-ItemProperty @GipSplat
if ($PropertyFound) {
# Does the property already have the requested value?
if ( ($PropertyFound.$Property) -ne $Value ) {
# If not, set the new value
$SipSplat = @{
Path = $KeyPath
Name = $PropertyName
Value = $Value
ErrorAction = 'Stop'
}
$msg = "Set Property $($PropertyName) under Key Path $($KeyPath) to Value $($Value)"
if ($PSCmdlet.ShouldProcess($KeyPath,$msg)) {
Set-ItemProperty @SipSplat
$ServiceRestartRequired = $true
}
}#END if ( -not ($PropertyFound.$Property) -eq $Value )
} else {
# If not, add the new value
$NipSplat = @{
Path = $KeyPath
Name = $PropertyName
Value = $Value
ErrorAction = 'Stop'
}
$msg = "Create Property $($PropertyName) under Key Path $($KeyPath) with Value $($Value)"
if ($PSCmdlet.ShouldProcess($KeyPath,$msg)) {
New-ItemProperty @NipSplat
$ServiceRestartRequired = $true
}
}#END if ($PropertyFound)
# Handle the service restart if needed
if ($ServiceRestartRequired) {
# Are there multiple services to restart?
if (@($ServiceName).count -gt 1) {
# Store the list of names in reverse order
$revSvcNames = [array]::Reverse($ServiceName)
} else {
$revSvcNames = $ServiceName
}
# Loop through services in order to stop them
foreach ($svcName in @($ServiceName)) {
# Capture the service as a WMI object
$svc = Get-WmiObject @WmiSplat
Write-Verbose "Restarting service $($svcName)..."
# Stop the service
if ($PSCmdlet.ShouldProcess($svcName,'Restart Service')) {
$svc.StopService()
}
# Pause
Start-Sleep -Seconds 1
# Refresh the object
$svc = Get-WmiObject @WmiSplat
# Wait for it to stop, max 60 seconds
for ($i = 0; $i -lt 12 -and $svc.State -ne 'Stopped'; $i++) {
# Pause
Start-Sleep -Seconds 5
# Refresh the object
$svc = Get-WmiObject @WmiSplat
}
}
# Pause for a bit
Start-Sleep 2
# Loop through services in reverse order to start them.
foreach ($svcName in @($revSvcNames)) {
# Capture the service as a WMI object
$svc = Get-WmiObject @WmiSplat
# Start the service
$svc.StartService()
# Pause
Start-Sleep -Seconds 1
# Refresh the object
$svc = Get-WmiObject @WmiSplat
# Wait for it to start, max 60 seconds
for ($i = 0; $i -lt 12 -and $svc.State -ne 'Running'; $i++) {
# Pause