Skip to content
Snippets Groups Projects
Commit ae364a62 authored by Andreas Lindemark's avatar Andreas Lindemark
Browse files

New script to choco upgrade -y all at startup and scsheduled

parent be312d6f
Branches
No related tags found
No related merge requests found
<#=============================================================================================================================
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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment