From ae364a629ac1a1275bd06a40b3bf6305b5d7f219 Mon Sep 17 00:00:00 2001
From: Andreas Lindemark <andreas.lindemark@liu.se>
Date: Mon, 10 Mar 2025 16:56:23 +0100
Subject: [PATCH] New script to choco upgrade -y all at startup and scsheduled

---
 .../Chocolatey/ScheduleChocolateyUpgrade.ps1  | 182 ++++++++++++++++++
 1 file changed, 182 insertions(+)
 create mode 100644 Windows/Chocolatey/ScheduleChocolateyUpgrade.ps1

diff --git a/Windows/Chocolatey/ScheduleChocolateyUpgrade.ps1 b/Windows/Chocolatey/ScheduleChocolateyUpgrade.ps1
new file mode 100644
index 0000000..8bc68e0
--- /dev/null
+++ b/Windows/Chocolatey/ScheduleChocolateyUpgrade.ps1
@@ -0,0 +1,182 @@
+<#=============================================================================================================================
+   Install and configure Chocolatey, also add a scheduled task to run "choco upgrade -y all" at computer startup and nightly
+=============================================================================================================================#>
+
+# Start the Script
+Write-Host "Starting script execution..."
+
+# Determine the name of the currently executing script without the extension
+$scriptName = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)
+
+# Set the log file path based on the script name
+$transcriptPath = "C:\Install Logs\$scriptName.log"
+
+# Start Transcript
+Start-Transcript -Path $transcriptPath
+
+# Determine the directory of the currently executing script
+$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
+
+# Load configuration
+$configPath = Join-Path -Path $scriptDirectory -ChildPath "config.json"
+$config = Get-Content -Path $configPath | ConvertFrom-Json
+
+# Function to check if a cmdlet exists
+function Test-Command {
+   param (
+      [string]$CommandName
+   )
+   $command = Get-Command -Name $CommandName -ErrorAction SilentlyContinue
+   return $null -ne $command
+}
+
+# Function to add a task, and remove the task if it already exists
+function New-CustomScheduledTask {
+   param (
+      [string]$TaskName,
+      [string]$TaskDescription,
+      [string]$Execute,
+      [string]$Argument,
+      [bool]$StartOnStartup = $false,
+      [bool]$StartupDelay = $false,
+      [array]$DailyTimes = @(),
+      [array]$Weekdays = @(),
+      [array]$RandomTimes = @(),
+      [array]$RandomDays = @(),
+      [string]$User = "System"
+   )
+
+   # Configure the action
+   $action = New-ScheduledTaskAction -Execute $Execute -Argument $Argument
+
+   # Create the triggers
+   $triggers = @()
+   if ($StartOnStartup) {
+      $triggers += New-ScheduledTaskTrigger -AtStartup
+   }
+
+   if ($DailyTimes.Count -gt 0) {
+      if ($Weekdays.Count -gt 0) {
+         foreach ($time in $DailyTimes) {
+            foreach ($day in $Weekdays) {
+               $triggers += New-ScheduledTaskTrigger -Weekly -DaysOfWeek $day -At $time
+            }
+         }
+      } else {
+         foreach ($time in $DailyTimes) {
+            $triggers += New-ScheduledTaskTrigger -Daily -At $time
+         }
+      }
+   }
+
+   if ($RandomTimes.Count -gt 0) {
+      $rand_time = $RandomTimes | Get-Random
+      if ($RandomDays.Count -gt 0) {
+         foreach ($day in $RandomDays) {
+            $triggers += New-ScheduledTaskTrigger -Weekly -DaysOfWeek $day -At $rand_time -RandomDelay "00:25:00"
+         }
+      } else {
+         $triggers += New-ScheduledTaskTrigger -Daily -At $rand_time -RandomDelay "00:25:00"
+      }
+   }
+
+   # Configure task settings
+   $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
+
+   # Check if the task already exists and delete it if it does
+   if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) {
+      Write-Host "Task $TaskName already exists. Deleting existing task..."
+      Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
+      Write-Host "Existing task deleted."
+   }
+
+   # Create the scheduled task
+   Register-ScheduledTask -Action $action -Trigger $triggers -TaskName $TaskName -Description $TaskDescription -Settings $settings -User $User
+}
+
+# Check if Chocolatey is installed
+if (Test-Command -CommandName "choco") {
+   Write-Host "Chocolatey is already installed."
+} else {
+   # Install Chocolatey
+   Write-Host "Chocolatey is not installed, please install."
+   Exit-PSSession
+}
+
+# Define the source path to the script to be copied
+$sourceScriptPath = Join-Path -Path $scriptDirectory -ChildPath "ChocolateyUpgrade.ps1"
+
+# Define the destination path
+$scriptPath = "C:\Windows\System32\Tasks\ChocolateyUpgrade.ps1"
+
+# Copy the script to a secure location
+try {
+   # Check if the source script exists
+   if (-Not (Test-Path -Path $sourceScriptPath)) {
+      Write-Host "Error: Source script $sourceScriptPath does not exist."
+      exit 1
+   }
+
+   Write-Host "Copying script from $sourceScriptPath to $scriptPath..."
+   Copy-Item -Path $sourceScriptPath -Destination $scriptPath -Force
+   Write-Host "Script copied successfully."
+} catch {
+   Write-Host "Error copying script: $_"
+   exit 1
+}
+
+# Extract task settings from the config file
+$taskSettings = $config.TaskSettings
+
+# Check PowerShell 7 path
+$pwshPath = (Get-Command pwsh -ErrorAction SilentlyContinue).Source
+
+if (-not $pwshPath) {
+   Write-Error "The path to PowerShell executable is not set."
+   return
+}
+
+# Check the path to PowerShell executable
+if ($pwshPath) {
+   # Define the argument for the script
+   $argument = "-File $scriptPath"
+
+   # Check for missing or null settings and apply defaults or skip
+   $startOnStartup = if ($null -ne $taskSettings.StartOnStartup) { $taskSettings.StartOnStartup } else { $true }
+   $startupDelay = if ($null -ne $taskSettings.StartupDelay) { $taskSettings.StartupDelay } else { $false }
+   $dailyTimes = if ($null -ne $taskSettings.DailyTimes) { $taskSettings.DailyTimes } else { @() }
+   $weekdays = if ($null -ne $taskSettings.Weekdays) { $taskSettings.Weekdays } else { @() }
+   $randomTimes = if ($null -ne $taskSettings.RandomTimes) { $taskSettings.RandomTimes } else { @() }
+   $randomDays = if ($null -ne $taskSettings.RandomDays) { $taskSettings.RandomDays } else { @() }
+
+   # Add -EnableRandomDelay parameter for the startup trigger if needed
+   $startupArgument = "$argument"
+   if ($StartupDelay) {
+      $startupArgument += " -EnableRandomDelay $true"
+   }
+
+      if (-not $pwshPath) {
+      Write-Error "The path to PowerShell executable is not set."
+      return
+   }
+
+   # Creating a scheduled task to update Chocolatey apps
+   New-CustomScheduledTask -TaskName "AutoUpdateChocolateyApps" `
+                           -TaskDescription "Automatically updates all Chocolatey applications on Startup" `
+                           -Execute $pwshPath `
+                           -Argument $startupArgument `
+                           -StartOnStartup $startOnStartup `
+                           -StartupDelay $startupDelay `
+                           -DailyTimes $dailyTimes `
+                           -Weekdays $weekdays `
+                           -RandomTimes $randomTimes `
+                           -RandomDays $randomDays
+} else {
+   Write-Error "PowerShell 7 installation failed or could not be found. Please ensure it is installed correctly."
+}
+
+# Stop Transcript
+Write-Host "Stopping transcript..."
+Stop-Transcript
+
+Write-Host "Script execution completed."
\ No newline at end of file
-- 
GitLab