-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStart-Update.ps1
87 lines (78 loc) · 2.9 KB
/
Start-Update.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
function Start-Update {
[CmdletBinding()]
param (
$Path = "$PSScriptRoot\update",
[switch]$Force,
[switch]$enableAll
)
Get-ChildItem "$PSScriptRoot\.util" -Filter "*.ps1" | ForEach-Object { . $_.FullName }
if ($Path -isnot [System.IO.DirectoryInfo]) {
$Path = New-Dir $Path
if ($Path -isnot [System.IO.DirectoryInfo]) {
throw "Path must be a directory"
}
}
if (!$Force -and !(Read-Timestamp "$Path\timestamp.txt")) {
Write-Verbose "Timestamp is current"
return
}
$checkCode = {
param ($ScriptPath)
Write-Verbose "Init: $ScriptPath"
$name, $latest, $searchTerm, $link, $cred = . $ScriptPath
$name, $latest, $searchTerm, $link | ForEach-Object {
if ([string]::isNullOrWhiteSpace($_)) { throw "Returned invalid Value: $ScriptPath" }
}
return $name, $latest, $searchTerm, $link, $cred
}
[System.Collections.ArrayList]$jobs = [System.Collections.ArrayList]::new()
$scripts = (Get-ChildItem "$PSScriptRoot\.util\scripts" -Filter "*.ps1").FullName
if ($enableAll) {
$scripts = ($scripts + (Get-ChildItem "$PSScriptRoot\.util\scripts\disabled" -Filter "*.ps1").FullName) | Sort-Object
}
foreach ($script in $scripts) {
$null = $jobs.Add((Start-Job -ArgumentList $script -ScriptBlock $checkCode -Verbose))
}
Write-Verbose "Jobs: $($jobs.Count)"
if ($jobs.Count -eq 0) {
Write-Warning "No update scripts!"
return
}
$results = Wait-JobWithProgress -Jobs $jobs -PassThru
$downloadCode = {
param($from, $to, $local, $cred)
${function:Copy-File} = ${using:function:Copy-File}
try {
Copy-File -From $from -To $to -Credential $cred
} catch {
$host.UI.WriteErrorLine("Copy-File failed: $($_.Exception.Message)`n$($_.ScriptStackTrace)")
return
}
if ($local) {
Remove-Item $local.FullName
}
}
$null = $jobs.Clear()
foreach ($result in $results) {
$local = Get-ChildItem -Path $Path -File -Filter $result[2]
if ($local) {
if ($local.name -eq $result[1]) {
Write-Host "latest: $($result[0])" -ForegroundColor Green
continue
}
}
$to = "$Path\$($result[1])"
$cred = $null
if ($result.length -ge 5) {
$cred = $result[4]
}
Write-Host "Updating: $($result[0]), Link: {$($result[3])} to: {$to}" -ForegroundColor Cyan
$null = $jobs.Add((Start-Job -ArgumentList $result[3], $to, $local, $cred -ScriptBlock $downloadCode -Verbose))
}
Write-Verbose "Downloads: $($jobs.Count)"
if ($jobs.Count -eq 0) {
return
}
Wait-JobWithProgress -Jobs $jobs -PassThru
Get-Date -Format "yyyyMMdd" | Out-File "$Path\timestamp.txt" -Encoding utf8 -Force -ErrorAction Stop
}