-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGet-3rdPartySoftware.ps1
3095 lines (2584 loc) · 271 KB
/
Get-3rdPartySoftware.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
<#
.INFO
Script: Get-3rdPartySoftware.ps1
Author: Richard Tracy
Email: [email protected]
Twitter: @rick2_1979
Website: www.powershellcrack.com
Last Update: 05/12/2020
Version: 2.1.5
Thanks to: michaelspice
.DISCLOSURE
THE SCRIPT IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. BY USING OR DISTRIBUTING THIS SCRIPT, YOU AGREE THAT
IN NO EVENT SHALL THE AUTHOR OR ANY AFFILATES BE HELD LIABLE FOR ANY CLAIM, ANY DAMAGES OR OTHER LIABILITY WHATSOEVER RESULTING
FROM USING OR DISTRIBUTION OF THIS SCRIPT AND SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY SPECIAL, CONSEQUENTIAL, INCIDENTAL
OR OTHER DIRECT OR INDIRECT DAMAGES. BACKUP UP ALL DATA BEFORE EXCUTING.
.SYNOPSIS
Download 3rd party Software and updates
.DESCRIPTION
Parses third party updates sites for download links, then downloads them to their respective folder.
Builds an XML file with details of each software for processing later
.PARAMETER DownloadPath
Specified an alternate download path. Defaults to relative path of script under software folder
.PARAMETER LogPath
Specified an alternate log path. Defaults to relative path of script under log folder
.EXAMPLE
powershell.exe -file "Get-3rdPartySoftware.ps1"
powershell.exe -file "Get-3rdPartySoftware.ps1" -DownloadPath D:\Repository\3rdPartySoftware\
powershell.exe -file "Get-3rdPartySoftware.ps1" -DownloadPath D:\Repository\3rdPartySoftware\ -LogPath D:\Logs\
.NOTES
This script is a web crawler; it literally crawls the publishers website and looks for html tags to find hyperlinks.
Then crawls those hyperlinks to grab versioning and eventually download the software. Each software has a custom crawler function, and is called at the very bottom of the script.
There is no API or JSON service it pulls from, besides firefox version control.
.LINK
https://michaelspice.net/windows/windows-software
.CHANGE LOG
2.1.5 - May 12, 2020 - Added Cleanup switch to all functions
2.1.4 - Oct 29, 2019 - Fixed content header function to use any webcontent; fixed firefox webrequest to use basic parsing. Added Firefox msi support
2.1.3 - Jul 15, 2019 - Added parameter to script for task secheduler calls. Added Creation data
2.1.1 - Jun 20, 2019 - Updated Firefox new URL; removed validatesets option for both to default; built function Get-WebRequestHeader
2.1.0 - Jun 18, 2019 - Added Adobe JDK and PowerBI update download
2.0.6 - Jun 13, 2019 - Added Adobe Acrobat DC Pro update download; set to clean log each time
2.0.5 - May 15, 2019 - Added Get-ScriptPath function to support VScode and ISE; fixed Set-UserSettings
2.0.2 - May 14, 2019 - Added description to clixml; removed java 7 and changed Chrome version check uri
2.0.1 = Apr 18, 2019 - Fixed chrome version check
2.0.0 - Nov 02, 2018 - Added Download function and standardized all scripts; build clixml
1.5.5 - Nov 01, 2017 - Added Github download
1.5.0 - Sep 12, 2017 - Functionalized all 3rd party software crawlers
1.1.1 - Mar 01, 2016 - added download for Firefox, 7Zip and VLC
1.0.0 - Feb 11, 2016 - initial
#>
##*===========================================================================
##* PARAMS
##*===========================================================================
param(
[Parameter(Mandatory=$false)]
$DownloadPath,
[Parameter(Mandatory=$false)]
$LogPath,
[Parameter(Mandatory=$false)]
[boolean]$OverwriteFiles = $false,
[Parameter(Mandatory=$false)]
[boolean]$CleanupFiles = $false
)
#==================================================
# FUNCTIONS
#==================================================
#region FUNCTION: Check if running in ISE
Function Test-IsISE {
# try...catch accounts for:
# Set-StrictMode -Version latest
try {
return ($null -ne $psISE);
}
catch {
return $false;
}
}
#endregion
#region FUNCTION: Check if running in Visual Studio Code
Function Test-VSCode{
if($env:TERM_PROGRAM -eq 'vscode') {
return $true;
}
Else{
return $false;
}
}
#endregion
#region FUNCTION: Find script path for either ISE or console
Function Get-ScriptPath {
<#
.SYNOPSIS
Finds the current script path even in ISE
#>
param([switch]$Parent)
if ($PSScriptRoot -eq "")
{
if (Test-IsISE)
{
If($Parent){Split-Path $psISE.CurrentFile.FullPath -Parent}Else{$psISE.CurrentFile.FullPath}
}
elseif(Test-VSCode){
((Get-ChildItem).Directory | select -Unique).FullName
}
else
{
$context = $psEditor.GetEditorContext()
$context.CurrentFile.Path
}
}
else
{
If($Parent){Split-Path $PSCommandPath -Parent}Else{$PSCommandPath}
}
}
#endregion
Function Format-DatePrefix {
[string]$LogTime = (Get-Date -Format 'HH:mm:ss.fff').ToString()
[string]$LogDate = (Get-Date -Format 'MM-dd-yyyy').ToString()
return ($LogDate + " " + $LogTime)
}
Function Write-LogEntry {
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string]$Message,
[Parameter(Mandatory=$false,Position=2)]
[string]$Source = '',
[parameter(Mandatory=$false)]
[ValidateSet(0,1,2,3,4)]
[int16]$Severity,
[parameter(Mandatory=$false, HelpMessage="Name of the log file that the entry will written to")]
[ValidateNotNullOrEmpty()]
[string]$OutputLogFile = $Global:LogFilePath,
[parameter(Mandatory=$false)]
[switch]$Outhost
)
Begin{
[string]$LogTime = (Get-Date -Format 'HH:mm:ss.fff').ToString()
[string]$LogDate = (Get-Date -Format 'MM-dd-yyyy').ToString()
[int32]$script:LogTimeZoneBias = [timezone]::CurrentTimeZone.GetUtcOffset([datetime]::Now).TotalMinutes
[string]$LogTimePlusBias = $LogTime + $script:LogTimeZoneBias
}
Process{
# Get the file name of the source script
Try {
If ($script:MyInvocation.Value.ScriptName) {
[string]$ScriptSource = Split-Path -Path $script:MyInvocation.Value.ScriptName -Leaf -ErrorAction 'Stop'
}
Else {
[string]$ScriptSource = Split-Path -Path $script:MyInvocation.MyCommand.Definition -Leaf -ErrorAction 'Stop'
}
}
Catch {
$ScriptSource = ''
}
If(!$Severity){$Severity = 1}
$LogFormat = "<![LOG[$Message]LOG]!>" + "<time=`"$LogTimePlusBias`" " + "date=`"$LogDate`" " + "component=`"$ScriptSource`" " + "context=`"$([Security.Principal.WindowsIdentity]::GetCurrent().Name)`" " + "type=`"$Severity`" " + "thread=`"$PID`" " + "file=`"$ScriptSource`">"
# Add value to log file
try {
Out-File -InputObject $LogFormat -Append -NoClobber -Encoding Default -FilePath $OutputLogFile -ErrorAction Stop
}
catch {
Write-Host ("[{0}] [{1}] :: Unable to append log entry to [{1}], error: {2}" -f $LogTimePlusBias,$ScriptSource,$OutputLogFile,$_.Exception.Message) -ForegroundColor Red
}
}
End{
If($Outhost -or $Global:OutTohost){
If($Source){
$OutputMsg = ("[{0}] [{1}] :: {2}" -f $LogTimePlusBias,$Source,$Message)
}
Else{
$OutputMsg = ("[{0}] [{1}] :: {2}" -f $LogTimePlusBias,$ScriptSource,$Message)
}
Switch($Severity){
0 {Write-Host $OutputMsg -ForegroundColor Green}
1 {Write-Host $OutputMsg -ForegroundColor Gray}
2 {Write-Warning $OutputMsg}
3 {Write-Host $OutputMsg -ForegroundColor Red}
4 {If($Global:Verbose){Write-Verbose $OutputMsg}}
default {Write-Host $OutputMsg}
}
}
}
}
Function Show-ProgressStatus {
<#
.SYNOPSIS
Shows task sequence secondary progress of a specific step
.DESCRIPTION
Adds a second progress bar to the existing Task Sequence Progress UI.
This progress bar can be updated to allow for a real-time progress of
a specific task sequence sub-step.
The Step and Max Step parameters are calculated when passed. This allows
you to have a "max steps" of 400, and update the step parameter. 100%
would be achieved when step is 400 and max step is 400. The percentages
are calculated behind the scenes by the Com Object.
.PARAMETER Message
The message to display the progress
.PARAMETER Step
Integer indicating current step
.PARAMETER MaxStep
Integer indicating 100%. A number other than 100 can be used.
.INPUTS
- Message: String
- Step: Long
- MaxStep: Long
.OUTPUTS
None
.EXAMPLE
Set's "Custom Step 1" at 30 percent complete
Show-ProgressStatus -Message "Running Custom Step 1" -Step 100 -MaxStep 300
.EXAMPLE
Set's "Custom Step 1" at 50 percent complete
Show-ProgressStatus -Message "Running Custom Step 1" -Step 150 -MaxStep 300
.EXAMPLE
Set's "Custom Step 1" at 100 percent complete
Show-ProgressStatus -Message "Running Custom Step 1" -Step 300 -MaxStep 300
#>
param(
[Parameter(Mandatory=$true)]
[string] $Message,
[Parameter(Mandatory=$true)]
[int]$Step,
[Parameter(Mandatory=$true)]
[int]$MaxStep,
[string]$SubMessage,
[int]$IncrementSteps,
[switch]$Outhost
)
Begin{
If($SubMessage){
$StatusMessage = ("{0} [{1}]" -f $Message,$SubMessage)
}
Else{
$StatusMessage = $Message
}
}
Process
{
If($Script:tsenv){
$Script:TSProgressUi.ShowActionProgress(`
$Script:tsenv.Value("_SMSTSOrgName"),`
$Script:tsenv.Value("_SMSTSPackageName"),`
$Script:tsenv.Value("_SMSTSCustomProgressDialogMessage"),`
$Script:tsenv.Value("_SMSTSCurrentActionName"),`
[Convert]::ToUInt32($Script:tsenv.Value("_SMSTSNextInstructionPointer")),`
[Convert]::ToUInt32($Script:tsenv.Value("_SMSTSInstructionTableSize")),`
$StatusMessage,`
$Step,`
$Maxstep)
}
Else{
Write-Progress -Activity "$Message ($Step of $Maxstep)" -Status $StatusMessage -PercentComplete (($Step / $Maxstep) * 100) -id 1
}
}
End{
}
}
Function Get-HrefMatches {
param(
## The filename to parse
[Parameter(Mandatory = $true)]
[string] $content,
## The Regular Expression pattern with which to filter
## the returned URLs
[string] $Pattern = "<\s*a\s*[^>]*?href\s*=\s*[`"']*([^`"'>]+)[^>]*?>"
)
$returnMatches = new-object System.Collections.ArrayList
## Match the regular expression against the content, and
## add all trimmed matches to our return list
$resultingMatches = [Regex]::Matches($content, $Pattern, "IgnoreCase")
foreach($match in $resultingMatches)
{
$cleanedMatch = $match.Groups[1].Value.Trim()
[void] $returnMatches.Add($cleanedMatch)
}
$returnMatches
}
Function Get-Hyperlinks {
param(
[Parameter(Mandatory = $true)]
[string] $content,
[string] $Pattern = "<A[^>]*?HREF\s*=\s*""([^""]+)""[^>]*?>([\s\S]*?)<\/A>"
)
$resultingMatches = [Regex]::Matches($content, $Pattern, "IgnoreCase")
$returnMatches = @()
foreach($match in $resultingMatches){
$LinkObjects = New-Object -TypeName PSObject
$LinkObjects | Add-Member -Type NoteProperty `
-Name Text -Value $match.Groups[2].Value.Trim()
$LinkObjects | Add-Member -Type NoteProperty `
-Name Href -Value $match.Groups[1].Value.Trim()
$returnMatches += $LinkObjects
}
$returnMatches
}
Function Get-WebContentHeader{
#https://stackoverflow.com/questions/41602754/get-website-metadata-such-as-title-description-from-given-url-using-powershell
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
#[Microsoft.PowerShell.Commands.HtmlWebResponseObject]$WebContent,
$WebContent,
[Parameter(Mandatory=$false)]
[ValidateSet('Keywords','Description','Title')]
[string]$Property
)
## -------- PARSE TITLE, DESCRIPTION AND KEYWORDS ----------
$resultTable = @{}
# Get the title
$resultTable.title = $WebContent.ParsedHtml.title
# Get the HTML Tag
$HtmlTag = $WebContent.ParsedHtml.childNodes | Where-Object {$_.nodename -eq 'HTML'}
# Get the HEAD Tag
$HeadTag = $HtmlTag.childNodes | Where-Object {$_.nodename -eq 'HEAD'}
# Get the Meta Tags
$MetaTags = $HeadTag.childNodes| Where-Object {$_.nodename -eq 'META'}
# You can view these using $metaTags | select outerhtml | fl
# Get the value on content from the meta tag having the attribute with the name keywords
$resultTable.keywords = $metaTags | Where-Object {$_.name -eq 'keywords'} | Select-Object -ExpandProperty content
# Do the same for description
$resultTable.description = $metaTags | Where-Object {$_.name -eq 'description'} | Select-Object -ExpandProperty content
# Return the table we have built as an object
switch($Property){
'Keywords' {Return $resultTable.keywords}
'Description' {Return $resultTable.description}
'Title' {Return $resultTable.title}
default {Return $resultTable}
}
}
Function Get-MSIInfo {
param(
[parameter(Mandatory=$true)]
[IO.FileInfo]$Path,
[parameter(Mandatory=$true)]
[ValidateSet("ProductCode","ProductVersion","ProductName")]
[string]$Property
)
try {
$WindowsInstaller = New-Object -ComObject WindowsInstaller.Installer
$MSIDatabase = $WindowsInstaller.GetType().InvokeMember("OpenDatabase","InvokeMethod",$Null,$WindowsInstaller,@($Path.FullName,0))
$Query = "SELECT Value FROM Property WHERE Property = '$($Property)'"
$View = $MSIDatabase.GetType().InvokeMember("OpenView","InvokeMethod",$null,$MSIDatabase,($Query))
$View.GetType().InvokeMember("Execute", "InvokeMethod", $null, $View, $null)
$Record = $View.GetType().InvokeMember("Fetch","InvokeMethod",$null,$View,$null)
$Value = $Record.GetType().InvokeMember("StringData","GetProperty",$null,$Record,1)
return $Value
Remove-Variable $WindowsInstaller
}
catch {
Write-Output $_.Exception.Message
}
}
Function Wait-FileUnlock {
Param(
[Parameter()]
[IO.FileInfo]$File,
[int]$SleepInterval=500
)
while(1){
try{
$fs=$file.Open('open','read', 'Read')
$fs.Close()
Write-Verbose "$file not open"
return
}
catch{
Start-Sleep -Milliseconds $SleepInterval
Write-Verbose '-'
}
}
}
Function IsFileLocked {
param(
[Parameter(Mandatory=$true)]
[string]$filePath
)
Rename-Item $filePath $filePath -ErrorVariable errs -ErrorAction SilentlyContinue
return ($errs.Count -ne 0)
}
Function Get-FileSize{
param(
[Parameter(Mandatory=$true)]
[string]$filePath
)
$result = Get-ChildItem $filePath | Measure-Object length -Sum | % {
New-Object psobject -prop @{
Size = $(
switch ($_.sum) {
{$_ -gt 1tb} { '{0:N2}TB' -f ($_ / 1tb); break }
{$_ -gt 1gb} { '{0:N2}GB' -f ($_ / 1gb); break }
{$_ -gt 1mb} { '{0:N2}MB' -f ($_ / 1mb); break }
{$_ -gt 1kb} { '{0:N2}KB' -f ($_ / 1Kb); break }
default { '{0}B ' -f $_ }
}
)
}
}
$result | Select-Object -ExpandProperty Size
}
Function Initialize-FileDownload {
param(
[Parameter(Mandatory=$false)]
[Alias("Title")]
[string]$Name,
[Parameter(Mandatory=$true,Position=1)]
[string]$Url,
[Parameter(Mandatory=$true,Position=2)]
[Alias("TargetDest")]
[string]$TargetFile
)
Begin{
## Get the name of this function
[string]${CmdletName} = $PSCmdlet.MyInvocation.MyCommand.Name
## Check running account
[Security.Principal.WindowsIdentity]$CurrentProcessToken = [Security.Principal.WindowsIdentity]::GetCurrent()
[Security.Principal.SecurityIdentifier]$CurrentProcessSID = $CurrentProcessToken.User
[boolean]$IsLocalSystemAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'LocalSystemSid')
[boolean]$IsLocalServiceAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'LocalServiceSid')
[boolean]$IsNetworkServiceAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'NetworkServiceSid')
[boolean]$IsServiceAccount = [boolean]($CurrentProcessToken.Groups -contains [Security.Principal.SecurityIdentifier]'S-1-5-6')
[boolean]$IsProcessUserInteractive = [Environment]::UserInteractive
}
Process
{
$ChildURLPath = $($url.split('/') | Select-Object -Last 1)
$uri = New-Object "System.Uri" "$url"
$request = [System.Net.HttpWebRequest]::Create($uri)
$request.set_Timeout(15000) #15 second timeout
$response = $request.GetResponse()
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
$responseStream = $response.GetResponseStream()
$targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $targetFile, Create
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
If($Name){$Label = $Name}Else{$Label = $ChildURLPath}
Write-LogEntry ("Initializing File Download from URL: {0}" -f $Url) -Source ${CmdletName} -Severity 1
while ($count -gt 0)
{
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
# display progress
# Check if script is running with no user session or is not interactive
If ( ($IsProcessUserInteractive -eq $false) -or $IsLocalSystemAccount -or $IsLocalServiceAccount -or $IsNetworkServiceAccount -or $IsServiceAccount) {
# display nothing
write-host "." -NoNewline
}
Else{
Show-ProgressStatus -Message ("Downloading: {0} ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -f $Label) -Step ([System.Math]::Floor($downloadedBytes/1024)) -MaxStep $totalLength
}
}
Start-Sleep 3
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
End{
#Write-Progress -activity "Finished downloading file '$($url.split('/') | Select-Object -Last 1)'"
If($Name){$Label = $Name}Else{$Label = $ChildURLPath}
Show-ProgressStatus -Message ("Finished downloading file: {0}" -f $Label) -Step $totalLength -MaxStep $totalLength
#change meta in file from internet to allow to run on system
If(Test-Path $TargetFile){Unblock-File $TargetFile -ErrorAction SilentlyContinue | Out-Null}
}
}
Function Get-FileProperties{
Param(
[io.fileinfo]$FilePath
)
$objFileProps = Get-item $filepath | Get-ItemProperty | Select-Object *
#Get required Comments extended attribute
$objShell = New-object -ComObject shell.Application
$objShellFolder = $objShell.NameSpace((get-item $filepath).Directory.FullName)
$objShellFile = $objShellFolder.ParseName((get-item $filepath).Name)
$strComments = $objShellfolder.GetDetailsOf($objshellfile,24)
$Version = [version]($strComments | Select-string -allmatches '(\d{1,4}\.){3}(\d{1,4})').matches.Value
$objShellFile = $null
$objShellFolder = $null
$objShell = $null
Add-Member -InputObject $objFileProps -MemberType NoteProperty -Name Version -Value $Version
Return $objFileProps
}
Function Get-FtpDir{
param(
[Parameter(Mandatory=$true)]
[string]$url,
[System.Management.Automation.PSCredential]$credentials
)
$request = [Net.WebRequest]::Create($url)
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
if ($credentials) { $request.Credentials = $credentials }
$response = $request.GetResponse()
$reader = New-Object IO.StreamReader $response.GetResponseStream()
$reader.ReadToEnd()
$reader.Close()
$response.Close()
}
##*===========================================================================
##* VARIABLES
##*===========================================================================
# Use function to get paths because Powershell ISE and other editors have differnt results
$scriptPath = Get-ScriptPath
[string]$scriptDirectory = Split-Path $scriptPath -Parent
[string]$scriptName = Split-Path $scriptPath -Leaf
[string]$scriptBaseName = [System.IO.Path]::GetFileNameWithoutExtension($scriptName)
$Global:Verbose = $false
If($PSBoundParameters.ContainsKey('Debug') -or $PSBoundParameters.ContainsKey('Verbose')){
$Global:Verbose = $PsBoundParameters.Get_Item('Verbose')
$VerbosePreference = 'Continue'
Write-Verbose ("[{0}] [{1}] :: VERBOSE IS ENABLED." -f (Format-DatePrefix),$scriptName)
}
Else{
$VerbosePreference = 'SilentlyContinue'
}
#Create log paths
If($LogPath){
$RelativeLogPath = $LogPath
}
Else{
$RelativeLogPath = Join-Path -Path $scriptDirectory -ChildPath 'Logs'
}
New-Item $RelativeLogPath -type directory -ErrorAction SilentlyContinue | Out-Null
#build log name
[string]$FileName = $scriptBaseName + '-' + (get-date -Format MM-dd-yyyy-hh-mm-ss) + '.log'
#build global log fullpath
$Global:LogFilePath = Join-Path $RelativeLogPath -ChildPath $FileName
#clean old log
if(Test-Path $Global:LogFilePath){remove-item -Path $Global:LogFilePath -ErrorAction SilentlyContinue | Out-Null}
Write-Host ("logging to file: {0}" -f $LogFilePath) -ForegroundColor Cyan
# BUILD FOLDER STRUCTURE
#=======================================================
#Create software path
If($DownloadPath){
$SoftwarePath = $DownloadPath
}
Else{
$SoftwarePath = Join-Path -Path $scriptDirectory -ChildPath 'Software'
#ensure directory is created
New-Item $SoftwarePath -type directory -ErrorAction SilentlyContinue | Out-Null
}
#check permissions on software path
Try{
(Get-Acl $SoftwarePath).Access | Where-Object{$_.IdentityReference -match $User.SamAccountName} | Select-Object IdentityReference,FileSystemRights | Out-Null
Write-LogEntry ("Downloading to [{0}]" -f $SoftwarePath) -Outhost
}
Catch{
Write-LogEntry ("Write permission to path [{0}] using credentials [{1}] are denied." -f $DownloadPath,$env:USERNAME) -Severity 3 -Outhost
Exit -1
}
# JAVA 8 - DOWNLOAD
#==================================================
Function Get-Java8 {
param(
[parameter(Mandatory=$true)]
[string]$RootPath,
[parameter(Mandatory=$true)]
[string]$FolderPath,
[parameter(Mandatory=$false)]
[ValidateSet('x86', 'x64')]
[string]$Arch,
[parameter(Mandatory=$false)]
[switch]$Overwrite,
[parameter(Mandatory=$false)]
[switch]$Cleanup,
[parameter(Mandatory=$false)]
[switch]$ReturnDetails
)
Begin{
## Get the name of this function
[string]${CmdletName} = $PSCmdlet.MyInvocation.MyCommand.Name
}
Process
{
$SoftObject = @()
$Publisher = "Oracle"
$Product = "Java 8"
$Language = 'en'
$ProductType = 'jre'
[System.Uri]$SourceURL = "http://www.java.com/"
[System.Uri]$DownloadURL = "http://www.java.com/$Language/download/manual.jsp"
Try{
## -------- CRAWL DOWNLOAD SOURCE ----------
#don't use basic parsing
$DownloadContent = Invoke-WebRequest $DownloadURL -ErrorAction Stop
Start-Sleep 3
## -------- PARSE VERSION ----------
$javaTitle = $DownloadContent.AllElements | Where-Object{$_.outerHTML -like "*Version*"} | Where-Object{$_.innerHTML -like "*Update*"} | Select-Object -Last 1 -ExpandProperty outerText
$parseVersion = $javaTitle.split("n ") | Select-Object -Last 3 #Split after n in version
$JavaMajor = $parseVersion[0]
$JavaMinor = $parseVersion[2]
$Version = "1." + $JavaMajor + ".0." + $JavaMinor
#$FileVersion = $parseVersion[0]+"u"+$parseVersion[2]
Write-LogEntry ("{0}'s latest version is: [{1} Update {2}]" -f $Product,$JavaMajor,$JavaMinor) -Severity 1 -Source ${CmdletName} -Outhost
$javaFileSuffix = ""
## -------- FIND DOWNLOAD LINKS ----------
#get the appropiate url based on architecture
switch($Arch){
'x86' {$DownloadLinks = $DownloadContent.AllElements | Where-Object{$_.innerHTML -eq "Windows Offline"} | Select-Object -ExpandProperty href | Select-Object -First 1;
$javaFileSuffix = "-windows-i586.exe","";
$archLabel = 'x86',''}
'x64' {$DownloadLinks = $DownloadContent.AllElements | Where-Object{$_.innerHTML -eq "Windows Offline (64-bit)"} | Select-Object -ExpandProperty href | Select-Object -First 1;
$javaFileSuffix = "-windows-x64.exe","";
$archLabel = 'x64',''}
default {$DownloadLinks = $DownloadContent.AllElements | Where-Object{$_.innerHTML -like "Windows Offline*"} | Select-Object -ExpandProperty href | Select-Object -First 2;
$javaFileSuffix = "-windows-i586.exe","-windows-x64.exe";
$archLabel = 'x86','x64'}
}
## -------- PARSE DESCRIPTION ----------
#$Description = Get-WebContentHeader -WebContent $content -Property Description
$AboutURL = ($DownloadContent.AllElements | Where-Object{$_.href -like "*/whatis*"}).href
$content = Invoke-WebRequest ($SourceURL.OriginalString + $AboutURL) -ErrorAction Stop
$Description = ($content.AllElements | Where-Object{$_.class -eq 'bodytext'} | Select-Object -First 2).innerText
## -------- BUILD FOLDERS ----------
$DestinationPath = Join-Path -Path $RootPath -ChildPath $FolderPath
If( !(Test-Path $DestinationPath)){
New-Item $DestinationPath -type directory -ErrorAction SilentlyContinue | Out-Null
}
#Remove all folders and files except the latest if they exist
If($Cleanup){
Get-ChildItem -Path $DestinationPath -Exclude sites.exception | Where-Object{$_.Name -notmatch $Version} | Foreach-Object($_) {
Remove-Item $_.fullname -Recurse -Force | Out-Null
Write-LogEntry ("Removed File: [{0}]" -f $_.fullname) -Severity 2 -Source ${CmdletName} -Outhost
}
}
#build Destination folder based on version
New-Item -Path "$DestinationPath\$Version" -type directory -ErrorAction SilentlyContinue | Out-Null
$i = 0
Foreach ($link in $DownloadLinks){
#build Download link from Root URL (if Needed)
$DownloadLink = $link
Write-LogEntry ("Validating Download Link: [{0}]" -f $DownloadLink) -Severity 1 -Source ${CmdletName} -Outhost
If($javaFileSuffix -eq 1){$i = 0}
$Filename = $ProductType + "-" + $JavaMajor + "u" + "$JavaMinor" + $javaFileSuffix[$i]
#$destination = $DestinationPath + "\" + $Filename
$destination = $DestinationPath + "\" + $Version + "\" + $Filename
$ExtensionType = [System.IO.Path]::GetExtension($fileName)
If ( (Test-Path $destination -ErrorAction SilentlyContinue) -and !$Overwrite){
Write-LogEntry ("File found: [{0}]. Ignoring download" -f $Filename) -Severity 0 -Source ${CmdletName} -Outhost
$downloaded=$True
}
Else{
## -------- DOWNLOAD SOFTWARE ----------
If((Test-Path $destination -ErrorAction SilentlyContinue) -and $Overwrite){$OverwriteMsg = "File found, Overwriting! "}Else{$OverwriteMsg = ""}
Try{
Write-LogEntry ("{0}Attempting to download: [{1}]..." -f $OverwriteMsg,$Filename) -Severity 1 -Source ${CmdletName} -Outhost
Initialize-FileDownload -Name ("{0}" -f $Filename) -Url $DownloadLink -TargetDest $destination
#$wc.DownloadFile($link, $destination)
Write-LogEntry ("Succesfully downloaded: {0} [{1} Update {2}] to [{3}]" -f $Product,$JavaMajor,$JavaMinor,$destination) -Severity 0 -Source ${CmdletName} -Outhost
$downloaded=$True
}
Catch {
Write-LogEntry ("Failed downloading: {0} to [{1}]: {2}" -f $Product,$destination,$_.Exception.Message) -Severity 3 -Source ${CmdletName} -Outhost
$downloaded=$False
}
}
#Build Object if exists
If(Test-Path $destination){
#grab the date on the file
$CreatedDate = Get-ChildItem $destination | Select-Object -ExpandProperty CreationTime | Get-Date -f "yyyy-MM-dd"
$FileSize = Get-FileSize $destination
#build array of software for inventory
$SoftObject += new-object psobject -property @{
FilePath=$destination
Version=$Version
File=$Filename
Publisher=$Publisher
Product=$Product
Arch=$archLabel[$i]
Language=$Language
FileType=$ExtensionType
ProductType=$ProductType
Downloaded=$downloaded
Description=$Description
DownloadDate=$CreatedDate
Size=$FileSize
}
}
$i++
}
}
catch {
Write-LogEntry ("Unable to download [{0}]. {1} Check Line: {2}" -f $Product,$_.Exception.Message,$_.InvocationInfo.ScriptLineNumber) -Severity 3 -Source ${CmdletName} -Outhost
}
}
End{
If($ReturnDetails){
return $SoftObject
}
}
}
# JDK - DOWNLOAD
#==================================================
Function Get-JDK {
param(
[parameter(Mandatory=$true)]
[string]$RootPath,
[parameter(Mandatory=$false)]
[string]$FolderPath,
[parameter(Mandatory=$false)]
[switch]$Overwrite,
[parameter(Mandatory=$false)]
[switch]$Cleanup,
[parameter(Mandatory=$false)]
[switch]$ReturnDetails
)
Begin{
## Get the name of this function
[string]${CmdletName} = $PSCmdlet.MyInvocation.MyCommand.Name
}
Process
{
$SoftObject = @()
$Publisher = "Oracle"
$Product = "Java Development Toolkit"
$Language = 'en'
$ProductType = 'jdk'
If(!$FolderPath){$FolderPath = $Product}
[System.Uri]$SourceURL = "https://www.oracle.com"
[System.Uri]$DownloadURL = "https://www.oracle.com/technetwork/java/javase/downloads/index.html"
# https://download.oracle.com/otn-pub/java/jdk/12.0.1+12/69cfe15208a647278a19ef0990eea691/jdk-12.0.1_windows-x64_bin.exe
Try{
## -------- CRAWL SOURCE ----------
$content = Invoke-WebRequest $SourceURL -ErrorAction Stop -UseBasicParsing
Start-Sleep 3
## -------- PARSE DESCRIPTION ----------
$Description = Get-WebContentHeader -WebContent $content -Property Description
## -------- CRAWL DOWNLOAD SOURCE ----------
$DownloadContent = Invoke-WebRequest $DownloadURL -ErrorAction Stop -UseBasicParsing
## -------- CRAWL LINK FOR VERSION ----------
$DetailLink = $SourceURL.OriginalString + (Get-HrefMatches -content [string]$DownloadContent | Where-Object {$_ -like "*$ProductType*"} | Select-Object -First 1)
$DetailContent = Invoke-WebRequest $DetailLink -ErrorAction Stop -UseBasicParsing
$ProductVersion = $DetailContent.RawContent | Select-String -Pattern "$ProductType\s+.*?(\d+\.)(\d+\.)(\d+)" -AllMatches | Select-Object -ExpandProperty matches | Select-Object -ExpandProperty value
$Version = ($ProductVersion -replace $ProductType,"").Trim()
Write-LogEntry ("{0}'s latest version is: [{1} Update {2}]" -f $Product,$JavaMajor,$JavaMinor) -Severity 1 -Source ${CmdletName} -Outhost
## -------- FIND DOWNLOAD LINKS ----------
#get the appropiate url based on architecture
$ParseLinks = $DetailContent.RawContent | Select-String -Pattern "(http[s]?|[s]?)(:\/\/)([^\s,]+)" -AllMatches | Select-Object -ExpandProperty matches | Select-Object -ExpandProperty value
$DownloadLinks = ($ParseLinks | Where-Object{$_ -match "_windows-x64_bin.exe"}) -replace '"',""
## -------- BUILD FOLDERS ----------
$DestinationPath = Join-Path -Path $RootPath -ChildPath $FolderPath
If( !(Test-Path $DestinationPath)){
New-Item $DestinationPath -type directory -ErrorAction SilentlyContinue | Out-Null
}
#Remove all folders and files except the latest if they exist
If($Cleanup){
Get-ChildItem -Path $DestinationPath -Exclude sites.exception | Where-Object{$_.Name -notmatch $Version} | Foreach-Object($_) {
Remove-Item $_.fullname -Recurse -Force | Out-Null
Write-LogEntry ("Removed File: [{0}]" -f $_.fullname) -Severity 2 -Source ${CmdletName} -Outhost
}
}
#build Destination folder based on version
New-Item -Path "$DestinationPath\$Version" -type directory -ErrorAction SilentlyContinue | Out-Null
Foreach ($link in $DownloadLinks){
#build Download link from Root URL (if Needed)
$DownloadLink = $link
Write-LogEntry ("Validating Download Link: [{0}]" -f $DownloadLink) -Severity 1 -Source ${CmdletName} -Outhost
$Filename = Split-Path $DownloadLink -leaf
$destination = $DestinationPath + "\" + $Version + "\" + $Filename
$ExtensionType = [System.IO.Path]::GetExtension($fileName)
If ( (Test-Path $destination -ErrorAction SilentlyContinue) -and !$Overwrite){
Write-LogEntry ("File found: [{0}]. Ignoring download" -f $Filename) -Severity 0 -Source ${CmdletName} -Outhost
$downloaded=$True
}
Else{
## -------- DOWNLOAD SOFTWARE ----------
If((Test-Path $destination -ErrorAction SilentlyContinue) -and $Overwrite){$OverwriteMsg = "File found, Overwriting! "}Else{$OverwriteMsg = ""}
Try{
Write-LogEntry ("{0}Attempting to download: [{1}]..." -f $OverwriteMsg,$Filename) -Severity 1 -Source ${CmdletName} -Outhost
Initialize-FileDownload -Name ("{0}" -f $Filename) -Url $DownloadLink -TargetDest $destination
#$wc.DownloadFile($link, $destination)
Write-LogEntry ("Succesfully downloaded: {0} [{1}] to [{2}]" -f $Product,$Version,$destination) -Severity 0 -Source ${CmdletName} -Outhost
$downloaded=$True
}
Catch {
Write-LogEntry ("Failed downloading: {0} to [{1}]: {2}" -f $Product,$destination,$_.Exception.Message) -Severity 3 -Source ${CmdletName} -Outhost
$downloaded=$False
}
}
#Build Object if exists
If(Test-Path $destination){
#grab the date on the file
$CreatedDate = Get-ChildItem $destination | Select-Object -ExpandProperty CreationTime | Get-Date -f "yyyy-MM-dd"
$FileSize = Get-FileSize $destination
#build array of software for inventory
$SoftObject += new-object psobject -property @{
FilePath=$destination
Version=$Version
File=$Filename
Publisher=$Publisher
Product=$Product
Arch="x64"
Language=$Language
FileType=$ExtensionType
ProductType=$ProductType
Downloaded=$downloaded
Description=$Description
DownloadDate=$CreatedDate
Size=$FileSize
}
}
$i++
}
}
catch {
Write-LogEntry ("Unable to download [{0}]. {1} Check Line: {2}" -f $Product,$_.Exception.Message,$_.InvocationInfo.ScriptLineNumber) -Severity 3 -Source ${CmdletName} -Outhost
}
}
End{
If($ReturnDetails){
return $SoftObject
}
}
}
# Chrome (x86 & x64) - DOWNLOAD
#==================================================
Function Get-Chrome {
param(
[parameter(Mandatory=$true)]
[string]$RootPath,
[parameter(Mandatory=$true)]
[string]$FolderPath,
[parameter(Mandatory=$false)]
[ValidateSet('Enterprise (x86)', 'Enterprise (x64)', 'Enterprise (Both)','Standalone (x86)','Standalone (x64)','Standalone (Both)')]
[string]$ArchType,
[parameter(Mandatory=$false)]
[switch]$Overwrite,
[parameter(Mandatory=$false)]
[switch]$Cleanup,
[parameter(Mandatory=$false)]
[switch]$ReturnDetails
)
Begin{
## Get the name of this function
[string]${CmdletName} = $PSCmdlet.MyInvocation.MyCommand.Name
}
Process
{
$SoftObject = @()
$Publisher = "Google"
$Product = "Chrome"
#$Language = 'en'
Try{
#[System.Uri]$SourceURL = "https://cloud.google.com/chrome-enterprise/browser/download/?h1=$Language"
[System.Uri]$SourceURL = "https://www.google.com/chrome/"
[String]$DownloadURL = "https://dl.google.com/dl/chrome/install"
#[System.Uri]$VersionURL = "https://www.whatismybrowser.com/guides/the-latest-version/chrome"
[System.Uri]$VersionURL = "https://chromereleases.googleblog.com/2019/05/stable-channel-update-for-desktop.html"