-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstall-ModuleMaintenance.ps1
More file actions
199 lines (156 loc) · 6.07 KB
/
Install-ModuleMaintenance.ps1
File metadata and controls
199 lines (156 loc) · 6.07 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
<#
.SYNOPSIS
Installs PSModuleMaintenance as a scheduled task.
.DESCRIPTION
Creates a Windows Scheduled Task that runs Invoke-PSModuleMaintenance.ps1 weekly.
The task runs as the current user with highest privileges.
.PARAMETER ScriptPath
Path to Invoke-PSModuleMaintenance.ps1. Defaults to same directory as this script.
.PARAMETER TaskName
Name for the scheduled task. Defaults to 'PSModuleMaintenance'.
.PARAMETER DayOfWeek
Day of the week to run. Defaults to 'Sunday'.
.PARAMETER Time
Time to run (24h format). Defaults to '03:00'.
.PARAMETER Uninstall
Remove the scheduled task instead of creating it.
.EXAMPLE
.\Install-ModuleMaintenance.ps1
.EXAMPLE
.\Install-ModuleMaintenance.ps1 -DayOfWeek Saturday -Time "04:30"
.EXAMPLE
.\Install-ModuleMaintenance.ps1 -Uninstall
.NOTES
Author: Haakon Wibe
Requires: Windows PowerShell 7+, Administrator privileges
#>
[CmdletBinding()]
param(
[Parameter()]
[string]$ScriptPath,
[Parameter()]
[string]$TaskName = 'PSModuleMaintenance',
[Parameter()]
[ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
[string]$DayOfWeek = 'Sunday',
[Parameter()]
[ValidatePattern('^\d{1,2}:\d{2}$')]
[string]$Time = '03:00',
[Parameter()]
[switch]$Uninstall
)
#Requires -Version 7.0
#Requires -RunAsAdministrator
$ErrorActionPreference = 'Stop'
# ============================================================================
# FUNCTIONS
# ============================================================================
function Test-ScheduledTaskExists {
param([string]$Name)
$task = Get-ScheduledTask -TaskName $Name -ErrorAction SilentlyContinue
return $null -ne $task
}
function Uninstall-MaintenanceTask {
param([string]$Name)
if (Test-ScheduledTaskExists -Name $Name) {
Write-Host "Removing scheduled task: $Name" -ForegroundColor Yellow
Unregister-ScheduledTask -TaskName $Name -Confirm:$false
Write-Host "Scheduled task removed successfully." -ForegroundColor Green
}
else {
Write-Host "Scheduled task '$Name' does not exist." -ForegroundColor Yellow
}
}
function Install-MaintenanceTask {
param(
[string]$Name,
[string]$Script,
[string]$Day,
[string]$RunTime
)
# Validate script exists
if (-not (Test-Path $Script)) {
throw "Script not found: $Script"
}
$scriptFullPath = (Resolve-Path $Script).Path
# Check if task already exists
if (Test-ScheduledTaskExists -Name $Name) {
Write-Host "Scheduled task '$Name' already exists. Updating..." -ForegroundColor Yellow
Unregister-ScheduledTask -TaskName $Name -Confirm:$false
}
# Get pwsh.exe path
$pwshPath = (Get-Command pwsh.exe -ErrorAction Stop).Source
# Build the action (hidden window for silent background execution)
$actionArgument = "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$scriptFullPath`""
$action = New-ScheduledTaskAction -Execute $pwshPath -Argument $actionArgument
# Build the trigger (weekly)
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek $Day -At $RunTime
# Build the principal (current user, run with highest privileges)
# Using Interactive logon - requires user to be logged in, but StartWhenAvailable will catch up
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$principal = New-ScheduledTaskPrincipal -UserId $currentUser -LogonType Interactive -RunLevel Highest
# Build settings
$settings = New-ScheduledTaskSettingsSet `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-StartWhenAvailable `
-RunOnlyIfNetworkAvailable `
-ExecutionTimeLimit (New-TimeSpan -Hours 4)
# Register the task
$taskParams = @{
TaskName = $Name
Action = $action
Trigger = $trigger
Principal = $principal
Settings = $settings
Description = "Weekly PowerShell module maintenance - updates modules and prunes old versions. https://github.com/haakonwibe/PSModuleMaintenance"
}
Register-ScheduledTask @taskParams | Out-Null
Write-Host ""
Write-Host "============================================" -ForegroundColor Cyan
Write-Host " Scheduled Task Created Successfully! " -ForegroundColor Green
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Task Name : $Name"
Write-Host "Script : $scriptFullPath"
Write-Host "Schedule : Every $Day at $RunTime"
Write-Host "Run As : $currentUser"
Write-Host "Elevated : Yes"
Write-Host ""
Write-Host "Logs will be written to: $env:ProgramData\PSModuleMaintenance\Logs" -ForegroundColor Gray
Write-Host ""
}
function Test-ManualRun {
param([string]$Name)
$response = Read-Host "Would you like to run the task now to verify it works? (y/N)"
if ($response -eq 'y' -or $response -eq 'Y') {
Write-Host "Starting task..." -ForegroundColor Yellow
Start-ScheduledTask -TaskName $Name
Write-Host "Task started. Check logs at: $env:ProgramData\PSModuleMaintenance\Logs" -ForegroundColor Green
}
}
# ============================================================================
# MAIN
# ============================================================================
try {
if ($Uninstall) {
Uninstall-MaintenanceTask -Name $TaskName
exit 0
}
# Determine script path
if ([string]::IsNullOrEmpty($ScriptPath)) {
$ScriptPath = Join-Path $PSScriptRoot 'Invoke-PSModuleMaintenance.ps1'
}
Write-Host ""
Write-Host "PSModuleMaintenance Installer" -ForegroundColor Cyan
Write-Host "=============================" -ForegroundColor Cyan
Write-Host ""
# Install the task
Install-MaintenanceTask -Name $TaskName -Script $ScriptPath -Day $DayOfWeek -RunTime $Time
# Offer test run
Test-ManualRun -Name $TaskName
}
catch {
Write-Host "ERROR: $_" -ForegroundColor Red
exit 1
}