Merge pull request #399 from jhochwald/main

Basic refactoring
pull/403/head
Romain 2023-09-20 08:52:51 +02:00 committed by GitHub
commit abe600e4ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 3391 additions and 2684 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,32 +1,36 @@
<# <#
.SYNOPSIS .SYNOPSIS
Handle user interaction from shortcuts and show a Toast notification Handle user interaction from shortcuts and show a Toast notification
.DESCRIPTION .DESCRIPTION
Act on shortcut run (DEFAULT: Check for updated Apps) Act on shortcut run (DEFAULT: Check for updated Apps)
.PARAMETER Logs .PARAMETER Logs
Open the Log file from Winget-AutoUpdate installation location Open the Log file from Winget-AutoUpdate installation location
.PARAMETER Help .PARAMETER Help
Open the Web Help page Open the Web Help page
https://github.com/Romanitho/Winget-AutoUpdate https://github.com/Romanitho/Winget-AutoUpdate
.EXAMPLE .EXAMPLE
.\user-run.ps1 -Logs .\user-run.ps1 -Logs
#> #>
[CmdletBinding()] [CmdletBinding()]
param( param (
[Parameter(Mandatory = $False)] [Switch] $Logs = $false, [Switch]
[Parameter(Mandatory = $False)] [Switch] $Help = $false $Logs = $False,
[Switch]
$Help = $False
) )
function Test-WAUisRunning { function Test-WAUisRunning
If (((Get-ScheduledTask -TaskName 'Winget-AutoUpdate').State -eq 'Running') -or ((Get-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext').State -eq 'Running')) { {
Return $True if (((Get-ScheduledTask -TaskName 'Winget-AutoUpdate' -ErrorAction SilentlyContinue).State -eq 'Running') -or ((Get-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -ErrorAction SilentlyContinue).State -eq 'Running'))
} {
return $True
}
} }
<# MAIN #> <# MAIN #>
@ -42,61 +46,72 @@ $Script:WorkingDir = $PSScriptRoot
Get-NotifLocale Get-NotifLocale
#Set common variables #Set common variables
$OnClickAction = "$WorkingDir\logs\updates.log" $OnClickAction = ('{0}\logs\updates.log' -f $WorkingDir)
$Button1Text = $NotifLocale.local.outputs.output[11].message $Button1Text = $NotifLocale.local.outputs.output[11].message
if ($Logs) { if ($Logs)
if (Test-Path "$WorkingDir\logs\updates.log") { {
Invoke-Item "$WorkingDir\logs\updates.log" if (Test-Path -Path ('{0}\logs\updates.log' -f $WorkingDir))
} {
else { Invoke-Item -Path ('{0}\logs\updates.log' -f $WorkingDir)
#Not available yet }
$Message = $NotifLocale.local.outputs.output[5].message else
$MessageType = "warning" {
Start-NotifTask -Message $Message -MessageType $MessageType -UserRun #Not available yet
} $Message = $NotifLocale.local.outputs.output[5].message
$MessageType = 'warning'
Start-NotifTask -Message $Message -MessageType $MessageType -UserRun
}
} }
elseif ($Help) { elseif ($Help)
Start-Process "https://github.com/Romanitho/Winget-AutoUpdate" {
Start-Process -FilePath 'https://github.com/Romanitho/Winget-AutoUpdate'
} }
else { else
try { {
#Check if WAU is currently running try
if (Test-WAUisRunning) { {
$Message = $NotifLocale.local.outputs.output[8].message # Check if WAU is currently running
$MessageType = "warning" if (Test-WAUisRunning)
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun {
break $Message = $NotifLocale.local.outputs.output[8].message
} $MessageType = 'warning'
#Run scheduled task Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
Get-ScheduledTask -TaskName "Winget-AutoUpdate" -ErrorAction Stop | Start-ScheduledTask -ErrorAction Stop break
#Starting check - Send notification }
$Message = $NotifLocale.local.outputs.output[6].message # Run scheduled task
$MessageType = "info" Get-ScheduledTask -TaskName 'Winget-AutoUpdate' -ErrorAction Stop | Start-ScheduledTask -ErrorAction Stop
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun # Starting check - Send notification
#Sleep until the task is done $Message = $NotifLocale.local.outputs.output[6].message
While (Test-WAUisRunning) { $MessageType = 'info'
Start-Sleep 3 Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
} # Sleep until the task is done
while (Test-WAUisRunning)
{
Start-Sleep -Seconds 3
}
#Test if there was a list_/winget_error # Test if there was a list_/winget_error
if (Test-Path "$WorkingDir\logs\error.txt") { if (Test-Path -Path ('{0}\logs\error.txt' -f $WorkingDir) -ErrorAction SilentlyContinue)
$MessageType = "error" {
$Critical = Get-Content "$WorkingDir\logs\error.txt" -Raw $MessageType = 'error'
$Critical = $Critical.Trim() $Critical = Get-Content -Path ('{0}\logs\error.txt' -f $WorkingDir) -Raw
$Critical = $Critical.Substring(0, [Math]::Min($Critical.Length, 50)) $Critical = $Critical.Trim()
$Message = "Critical:`n$Critical..." $Critical = $Critical.Substring(0, [Math]::Min($Critical.Length, 50))
} $Message = ("Critical:`n{0}..." -f $Critical)
else { }
$MessageType = "success" else
$Message = $NotifLocale.local.outputs.output[9].message {
} $MessageType = 'success'
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun $Message = $NotifLocale.local.outputs.output[9].message
} }
catch { Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
#Check failed - Just send notification }
$Message = $NotifLocale.local.outputs.output[7].message catch
$MessageType = "error" {
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun # Check failed - Just send notification
} $Message = $NotifLocale.local.outputs.output[7].message
$MessageType = 'error'
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
}
} }

View File

@ -1,85 +1,97 @@
<# <#
.SYNOPSIS .SYNOPSIS
Uninstall Winget-AutoUpdate Uninstall Winget-AutoUpdate
.DESCRIPTION .DESCRIPTION
Uninstalls Winget-AutoUpdate (DEFAULT: clean old install) Uninstalls Winget-AutoUpdate (DEFAULT: clean old install)
https://github.com/Romanitho/Winget-AutoUpdate https://github.com/Romanitho/Winget-AutoUpdate
.PARAMETER NoClean .PARAMETER NoClean
Uninstall Winget-AutoUpdate (keep critical files) Uninstall Winget-AutoUpdate (keep critical files)
.EXAMPLE .EXAMPLE
.\WAU-Uninstall.ps1 -NoClean .\WAU-Uninstall.ps1 -NoClean
#> #>
[CmdletBinding()] [CmdletBinding()]
param( param (
[Parameter(Mandatory = $False)] [Switch] $NoClean = $false [Switch]
$NoClean = $false
) )
Write-Host "`n" Write-Host -Object "`n"
Write-Host "`t 888 888 d8888 888 888" -ForegroundColor Magenta Write-Host -Object "`t 888 888 d8888 888 888" -ForegroundColor Magenta
Write-Host "`t 888 o 888 d88888 888 888" -ForegroundColor Magenta Write-Host -Object "`t 888 o 888 d88888 888 888" -ForegroundColor Magenta
Write-Host "`t 888 d8b 888 d88P888 888 888" -ForegroundColor Magenta Write-Host -Object "`t 888 d8b 888 d88P888 888 888" -ForegroundColor Magenta
Write-Host "`t 888 d888b 888 d88P 888 888 888" -ForegroundColor Magenta Write-Host -Object "`t 888 d888b 888 d88P 888 888 888" -ForegroundColor Magenta
Write-Host "`t 888d88888b888 d88P 888 888 888" -ForegroundColor Magenta Write-Host -Object "`t 888d88888b888 d88P 888 888 888" -ForegroundColor Magenta
Write-Host "`t 88888P Y88888 d88P 888 888 888" -ForegroundColor Cyan Write-Host -Object "`t 88888P Y88888 d88P 888 888 888" -ForegroundColor Cyan
Write-Host "`t 8888P Y8888 d88P 888 888 888" -ForegroundColor Magenta Write-Host -Object "`t 8888P Y8888 d88P 888 888 888" -ForegroundColor Magenta
Write-Host "`t 888P Y888 d88P 888 Y8888888P`n" -ForegroundColor Magenta Write-Host -Object "`t 888P Y888 d88P 888 Y8888888P`n" -ForegroundColor Magenta
Write-Host "`t Winget-AutoUpdate`n" -ForegroundColor Cyan Write-Host -Object "`t Winget-AutoUpdate`n" -ForegroundColor Cyan
Write-Host "`t https://github.com/Romanitho/Winget-AutoUpdate`n" -ForegroundColor Magenta Write-Host -Object "`t https://github.com/Romanitho/Winget-AutoUpdate`n" -ForegroundColor Magenta
Write-Host "`t________________________________________________________`n`n" Write-Host -Object "`t________________________________________________________`n`n"
try { try
Write-host "Uninstalling WAU..." -ForegroundColor Yellow {
#Get registry install location Write-Host -Object 'Uninstalling WAU...' -ForegroundColor Yellow
$InstallLocation = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate\" -Name InstallLocation
#Check if installed location exists and delete # Get registry install location
if (Test-Path ($InstallLocation)) { $InstallLocation = (Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate\' -Name InstallLocation)
if (!$NoClean) { # Check if installed location exists and delete
Remove-Item "$InstallLocation\*" -Force -Recurse -Exclude "*.log" if (Test-Path -Path ($InstallLocation))
} {
else { if (!$NoClean)
#Keep critical files {
Get-ChildItem -Path $InstallLocation -Exclude *.txt, mods, logs | Remove-Item -Recurse -Force $null = (Remove-Item -Path ('{0}\*' -f $InstallLocation) -Force -Confirm:$false -Recurse -Exclude '*.log')
} }
Get-ScheduledTask -TaskName "Winget-AutoUpdate" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$False else
Get-ScheduledTask -TaskName "Winget-AutoUpdate-Notify" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$False {
Get-ScheduledTask -TaskName "Winget-AutoUpdate-UserContext" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$False # Keep critical files
& reg delete "HKCR\AppUserModelId\Windows.SystemToast.Winget.Notification" /f | Out-Null $null = (Get-ChildItem -Path $InstallLocation -Exclude *.txt, mods, logs | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue)
& reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" /f | Out-Null }
if (Test-Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate") { $null = (Get-ScheduledTask -TaskName 'Winget-AutoUpdate' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false)
& reg delete "HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" /f | Out-Null $null = (Get-ScheduledTask -TaskName 'Winget-AutoUpdate-Notify' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false)
} $null = (Get-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false)
$null = & "$env:windir\system32\reg.exe" delete 'HKCR\AppUserModelId\Windows.SystemToast.Winget.Notification' /f
$null = & "$env:windir\system32\reg.exe" delete 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate' /f
if ((Test-Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)")) { if (Test-Path -Path 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate' -ErrorAction SilentlyContinue)
Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force | Out-Null {
} $null = & "$env:windir\system32\reg.exe" delete 'HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate' /f
}
if ((Test-Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk")) { if ((Test-Path -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)"))
Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force | Out-Null {
} $null = (Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force -Confirm:$false)
}
#Remove Intune Logs if they are existing if ((Test-Path -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk"))
if (Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log") { {
Remove-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -Force -ErrorAction SilentlyContinue | Out-Null $null = (Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force -Confirm:$false)
} }
if (Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log") {
Remove-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -Force -ErrorAction SilentlyContinue | Out-Null
}
Write-host "Uninstallation succeeded!" -ForegroundColor Green # Remove Intune Logs if they are existing
} if (Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log")
else { {
Write-host "$InstallLocation not found! Uninstallation failed!" -ForegroundColor Red $null = (Remove-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -Force -Confirm:$false -ErrorAction SilentlyContinue)
} }
if (Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -ErrorAction SilentlyContinue)
{
$null = (Remove-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -Force -Confirm:$false -ErrorAction SilentlyContinue)
}
Write-Host -Object 'Uninstallation succeeded!' -ForegroundColor Green
}
else
{
Write-Host -Object ('{0} not found! Uninstallation failed!' -f $InstallLocation) -ForegroundColor Red
}
} }
catch { catch
Write-host "`nUninstallation failed! Run as admin ?" -ForegroundColor Red {
Write-Host -Object "`nUninstallation failed! Run as admin ?" -ForegroundColor Red
} }
Start-sleep 2 Start-Sleep -Seconds 2

View File

@ -1,24 +1,29 @@
#Send Notify Script # Send Notify Script
#get xml notif config # get xml notif config
$WAUinstalledPath = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate\" -Name InstallLocation $WAUinstalledPath = (Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate\' -Name InstallLocation)
[xml]$NotifConf = Get-Content "$WAUinstalledPath\config\notif.xml" -Encoding UTF8 -ErrorAction SilentlyContinue [xml]$NotifConf = (Get-Content -Path "$WAUinstalledPath\config\notif.xml" -Encoding UTF8 -ErrorAction SilentlyContinue)
if (!($NotifConf)) {
break if (!($NotifConf))
{
break
} }
#Load Assemblies # Load Assemblies
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null $null = (Add-Type -AssemblyName Windows.Data)
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null $null = (Add-Type -AssemblyName Windows.UI)
#Prepare XML $null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
# Prepare XML
$ToastXml = [Windows.Data.Xml.Dom.XmlDocument]::New() $ToastXml = [Windows.Data.Xml.Dom.XmlDocument]::New()
$ToastXml.LoadXml($NotifConf.OuterXml) $ToastXml.LoadXml($NotifConf.OuterXml)
#Specify Launcher App ID # Specify Launcher App ID
$LauncherID = "Windows.SystemToast.Winget.Notification" $LauncherID = 'Windows.SystemToast.Winget.Notification'
#Prepare and Create Toast # Prepare and Create Toast
$ToastMessage = [Windows.UI.Notifications.ToastNotification]::New($ToastXML) $ToastMessage = [Windows.UI.Notifications.ToastNotification]::New($ToastXml)
$ToastMessage.Tag = $NotifConf.toast.tag $ToastMessage.Tag = $NotifConf.toast.tag
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($LauncherID).Show($ToastMessage) [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($LauncherID).Show($ToastMessage)

View File

@ -1,345 +1,419 @@
<# LOAD FUNCTIONS #> <# LOAD FUNCTIONS #>
#Get the Working Dir # Get the Working Dir
$Script:WorkingDir = $PSScriptRoot $Script:WorkingDir = $PSScriptRoot
#Get Functions
Get-ChildItem "$WorkingDir\functions" | ForEach-Object { . $_.FullName }
# Get Functions
Get-ChildItem -Path "$WorkingDir\functions" | ForEach-Object {
. $_.FullName
}
<# MAIN #> <# MAIN #>
#Check if running account is system or interactive logon # Check if running account is system or interactive logon
$Script:IsSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().IsSystem $Script:IsSystem = [Security.Principal.WindowsIdentity]::GetCurrent().IsSystem
#Run log initialisation function # Run log initialisation function
Start-Init Start-Init
#Get WAU Configurations # Get WAU Configurations
$Script:WAUConfig = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" $Script:WAUConfig = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate')
#Log running context and more... #Log running context and more...
if ($IsSystem) { if ($IsSystem)
Write-ToLog "Running in System context" {
Write-ToLog 'Running in System context'
#Get and set Domain/Local Policies (GPO) #Get and set Domain/Local Policies (GPO)
$ActivateGPOManagement, $ChangedSettings = Get-Policies $ActivateGPOManagement, $ChangedSettings = Get-Policies
if ($ActivateGPOManagement) { if ($ActivateGPOManagement)
Write-ToLog "Activated WAU GPO Management detected, comparing..." {
if ($null -ne $ChangedSettings -and $ChangedSettings -ne 0) { Write-ToLog 'Activated WAU GPO Management detected, comparing...'
Write-ToLog "Changed settings detected and applied" "Yellow" if ($null -ne $ChangedSettings -and $ChangedSettings -ne 0)
} {
else { Write-ToLog 'Changed settings detected and applied' 'Yellow'
Write-ToLog "No Changed settings detected" "Yellow" }
} else
} {
Write-ToLog 'No Changed settings detected' 'Yellow'
}
}
# Maximum number of log files to keep. Default is 3. Setting MaxLogFiles to 0 will keep all log files. # Maximum number of log files to keep. Default is 3. Setting MaxLogFiles to 0 will keep all log files.
$MaxLogFiles = $WAUConfig.WAU_MaxLogFiles $MaxLogFiles = $WAUConfig.WAU_MaxLogFiles
if ($null -eq $MaxLogFiles) { if ($null -eq $MaxLogFiles)
[int32] $MaxLogFiles = 3 {
} [int]$MaxLogFiles = 3
else { }
[int32] $MaxLogFiles = $MaxLogFiles else
} {
[int]$MaxLogFiles = $MaxLogFiles
}
# Maximum size of log file. # Maximum size of log file.
$MaxLogSize = $WAUConfig.WAU_MaxLogSize $MaxLogSize = $WAUConfig.WAU_MaxLogSize
if (!$MaxLogSize) { if (!$MaxLogSize)
[int64] $MaxLogSize = 1048576 # in bytes, default is 1048576 = 1 MB {
} [long]$MaxLogSize = 1048576 # in bytes, default is 1048576 = 1 MB
else { }
[int64] $MaxLogSize = $MaxLogSize else
} {
[long]$MaxLogSize = $MaxLogSize
}
#LogRotation if System #LogRotation if System
$LogRotate = Invoke-LogRotation $LogFile $MaxLogFiles $MaxLogSize $LogRotate = Invoke-LogRotation $LogFile $MaxLogFiles $MaxLogSize
if ($LogRotate -eq $False) { if ($LogRotate -eq $False)
Write-ToLog "An Exception occured during Log Rotation..." {
} Write-ToLog 'An Exception occured during Log Rotation...'
}
#Run post update actions if necessary if run as System #Run post update actions if necessary if run as System
if (!($WAUConfig.WAU_PostUpdateActions -eq 0)) { if (!($WAUConfig.WAU_PostUpdateActions -eq 0))
Invoke-PostUpdateActions {
} Invoke-PostUpdateActions
#Run Scope Machine funtion if run as System }
$SettingsPath = "$Env:windir\system32\config\systemprofile\AppData\Local\Microsoft\WinGet\Settings\defaultState\settings.json" #Run Scope Machine funtion if run as System
Add-ScopeMachine $SettingsPath $SettingsPath = "$Env:windir\system32\config\systemprofile\AppData\Local\Microsoft\WinGet\Settings\defaultState\settings.json"
Add-ScopeMachine $SettingsPath
} }
else { else
Write-ToLog "Running in User context" {
Write-ToLog 'Running in User context'
} }
#Get Notif Locale function #Get Notif Locale function
$LocaleDisplayName = Get-NotifLocale $LocaleDisplayName = Get-NotifLocale
Write-ToLog "Notification Level: $($WAUConfig.WAU_NotificationLevel). Notification Language: $LocaleDisplayName" "Cyan" Write-ToLog "Notification Level: $($WAUConfig.WAU_NotificationLevel). Notification Language: $LocaleDisplayName" 'Cyan'
#Check network connectivity #Check network connectivity
if (Test-Network) { if (Test-Network)
#Check if Winget is installed and get Winget cmd {
$TestWinget = Get-WingetCmd #Check if Winget is installed and get Winget cmd
$TestWinget = Get-WingetCmd
if ($TestWinget) { if ($TestWinget)
#Get Current Version {
$WAUCurrentVersion = $WAUConfig.DisplayVersion #Get Current Version
Write-ToLog "WAU current version: $WAUCurrentVersion" $WAUCurrentVersion = $WAUConfig.DisplayVersion
if ($IsSystem) { Write-ToLog "WAU current version: $WAUCurrentVersion"
#Check if WAU update feature is enabled or not if run as System if ($IsSystem)
$WAUDisableAutoUpdate = $WAUConfig.WAU_DisableAutoUpdate {
#If yes then check WAU update if run as System #Check if WAU update feature is enabled or not if run as System
if ($WAUDisableAutoUpdate -eq 1) { $WAUDisableAutoUpdate = $WAUConfig.WAU_DisableAutoUpdate
Write-ToLog "WAU AutoUpdate is Disabled." "Gray" #If yes then check WAU update if run as System
if ($WAUDisableAutoUpdate -eq 1)
{
Write-ToLog 'WAU AutoUpdate is Disabled.' 'Gray'
}
else
{
Write-ToLog 'WAU AutoUpdate is Enabled.' 'Green'
#Get Available Version
$Script:WAUAvailableVersion = Get-WAUAvailableVersion
#Compare
if ([version]$WAUAvailableVersion.Replace('-', '.') -ne [version]$WAUCurrentVersion.Replace('-', '.'))
{
#If new version is available, update it
Write-ToLog "WAU Available version: $WAUAvailableVersion" 'Yellow'
Update-WAU
} }
else { else
Write-ToLog "WAU AutoUpdate is Enabled." "Green" {
#Get Available Version Write-ToLog 'WAU is up to date.' 'Green'
$Script:WAUAvailableVersion = Get-WAUAvailableVersion
#Compare
if ([version]$WAUAvailableVersion.Replace("-", ".") -ne [version]$WAUCurrentVersion.Replace("-", ".")) {
#If new version is available, update it
Write-ToLog "WAU Available version: $WAUAvailableVersion" "Yellow"
Update-WAU
}
else {
Write-ToLog "WAU is up to date." "Green"
}
} }
}
#Delete previous list_/winget_error (if they exist) if run as System #Delete previous list_/winget_error (if they exist) if run as System
if (Test-Path "$WorkingDir\logs\error.txt") { if (Test-Path -Path "$WorkingDir\logs\error.txt")
Remove-Item "$WorkingDir\logs\error.txt" -Force {
Remove-Item -Path "$WorkingDir\logs\error.txt" -Force
}
#Get External ListPath if run as System
if ($WAUConfig.WAU_ListPath)
{
$ListPathClean = $($WAUConfig.WAU_ListPath.TrimEnd(' ', '\', '/'))
Write-ToLog "WAU uses External Lists from: $ListPathClean"
if ($ListPathClean -ne 'GPO')
{
$NewList = Test-ListPath $ListPathClean $WAUConfig.WAU_UseWhiteList $WAUConfig.InstallLocation.TrimEnd(' ', '\')
if ($ReachNoPath)
{
Write-ToLog "Couldn't reach/find/compare/copy from $ListPathClean..." 'Red'
if ($ListPathClean -notlike 'http*')
{
if (Test-Path -Path "$ListPathClean" -PathType Leaf)
{
Write-ToLog 'PATH must end with a Directory, not a File...' 'Red'
}
}
else
{
if ($ListPathClean -match '_apps.txt')
{
Write-ToLog 'PATH must end with a Directory, not a File...' 'Red'
}
}
$Script:ReachNoPath = $False
}
if ($NewList)
{
Write-ToLog "Newer List downloaded/copied to local path: $($WAUConfig.InstallLocation.TrimEnd(' ', '\'))" 'Yellow'
}
else
{
if ($WAUConfig.WAU_UseWhiteList -and (Test-Path -Path "$WorkingDir\included_apps.txt"))
{
Write-ToLog 'List (white) is up to date.' 'Green'
}
elseif (!$WAUConfig.WAU_UseWhiteList -and (Test-Path -Path "$WorkingDir\excluded_apps.txt"))
{
Write-ToLog 'List (black) is up to date.' 'Green'
}
else
{
Write-ToLog "Critical: White/Black List doesn't exist, exiting..." 'Red'
New-Item -Path "$WorkingDir\logs\error.txt" -Value "White/Black List doesn't exist" -Force
exit 1
}
}
} }
}
#Get External ListPath if run as System #Get External ModsPath if run as System
if ($WAUConfig.WAU_ListPath) { if ($WAUConfig.WAU_ModsPath)
$ListPathClean = $($WAUConfig.WAU_ListPath.TrimEnd(" ", "\", "/")) {
Write-ToLog "WAU uses External Lists from: $ListPathClean" $ModsPathClean = $($WAUConfig.WAU_ModsPath.TrimEnd(' ', '\', '/'))
if ($ListPathClean -ne "GPO") { Write-ToLog "WAU uses External Mods from: $ModsPathClean"
$NewList = Test-ListPath $ListPathClean $WAUConfig.WAU_UseWhiteList $WAUConfig.InstallLocation.TrimEnd(" ", "\") if ($WAUConfig.WAU_AzureBlobSASURL)
if ($ReachNoPath) { {
Write-ToLog "Couldn't reach/find/compare/copy from $ListPathClean..." "Red" $NewMods, $DeletedMods = Test-ModsPath $ModsPathClean $WAUConfig.InstallLocation.TrimEnd(' ', '\') $WAUConfig.WAU_AzureBlobSASURL.TrimEnd(' ')
if ($ListPathClean -notlike "http*") {
if (Test-Path -Path "$ListPathClean" -PathType Leaf) {
Write-ToLog "PATH must end with a Directory, not a File..." "Red"
}
}
else {
if ($ListPathClean -match "_apps.txt") {
Write-ToLog "PATH must end with a Directory, not a File..." "Red"
}
}
$Script:ReachNoPath = $False
}
if ($NewList) {
Write-ToLog "Newer List downloaded/copied to local path: $($WAUConfig.InstallLocation.TrimEnd(" ", "\"))" "Yellow"
}
else {
if ($WAUConfig.WAU_UseWhiteList -and (Test-Path "$WorkingDir\included_apps.txt")) {
Write-ToLog "List (white) is up to date." "Green"
}
elseif (!$WAUConfig.WAU_UseWhiteList -and (Test-Path "$WorkingDir\excluded_apps.txt")) {
Write-ToLog "List (black) is up to date." "Green"
}
else {
Write-ToLog "Critical: White/Black List doesn't exist, exiting..." "Red"
New-Item "$WorkingDir\logs\error.txt" -Value "White/Black List doesn't exist" -Force
Exit 1
}
}
}
} }
else
#Get External ModsPath if run as System {
if ($WAUConfig.WAU_ModsPath) { $NewMods, $DeletedMods = Test-ModsPath $ModsPathClean $WAUConfig.InstallLocation.TrimEnd(' ', '\')
$ModsPathClean = $($WAUConfig.WAU_ModsPath.TrimEnd(" ", "\", "/"))
Write-ToLog "WAU uses External Mods from: $ModsPathClean"
if ($WAUConfig.WAU_AzureBlobSASURL) {
$NewMods, $DeletedMods = Test-ModsPath $ModsPathClean $WAUConfig.InstallLocation.TrimEnd(" ", "\") $WAUConfig.WAU_AzureBlobSASURL.TrimEnd(" ")
}
else {
$NewMods, $DeletedMods = Test-ModsPath $ModsPathClean $WAUConfig.InstallLocation.TrimEnd(" ", "\")
}
if ($ReachNoPath) {
Write-ToLog "Couldn't reach/find/compare/copy from $ModsPathClean..." "Red"
$Script:ReachNoPath = $False
}
if ($NewMods -gt 0) {
Write-ToLog "$NewMods newer Mods downloaded/copied to local path: $($WAUConfig.InstallLocation.TrimEnd(" ", "\"))\mods" "Yellow"
}
else {
if (Test-Path "$WorkingDir\mods\*.ps1") {
Write-ToLog "Mods are up to date." "Green"
}
else {
Write-ToLog "No Mods are implemented..." "Yellow"
}
}
if ($DeletedMods -gt 0) {
Write-ToLog "$DeletedMods Mods deleted (not externally managed) from local path: $($WAUConfig.InstallLocation.TrimEnd(" ", "\"))\mods" "Red"
}
} }
if ($ReachNoPath)
#Test if _WAU-mods.ps1 exist: Mods for WAU (if Network is active/any Winget is installed/running as SYSTEM) {
$Mods = "$WorkingDir\mods" Write-ToLog "Couldn't reach/find/compare/copy from $ModsPathClean..." 'Red'
if (Test-Path "$Mods\_WAU-mods.ps1") { $Script:ReachNoPath = $False
Write-ToLog "Running Mods for WAU..." "Yellow"
& "$Mods\_WAU-mods.ps1"
$ModsExitCode = $LASTEXITCODE
#If _WAU-mods.ps1 has ExitCode 1 - Re-run WAU
if ($ModsExitCode -eq 1) {
Write-ToLog "Re-run WAU"
Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"$WorkingDir\winget-upgrade.ps1`""
Exit
}
} }
if ($NewMods -gt 0)
} {
Write-ToLog "$NewMods newer Mods downloaded/copied to local path: $($WAUConfig.InstallLocation.TrimEnd(' ', '\'))\mods" 'Yellow'
if ($($WAUConfig.WAU_ListPath) -eq "GPO") {
$Script:GPOList = $True
}
#Get White or Black list
if ($WAUConfig.WAU_UseWhiteList -eq 1) {
Write-ToLog "WAU uses White List config"
$toUpdate = Get-IncludedApps
$UseWhiteList = $true
}
else {
Write-ToLog "WAU uses Black List config"
$toSkip = Get-ExcludedApps
}
#Fix and count the array if GPO List as ERROR handling!
if ($GPOList) {
if ($UseWhiteList) {
$WhiteList = $toUpdate.GetUpperBound(0)
if ($null -eq $WhiteList) {
Write-ToLog "Critical: Whitelist doesn't exist in GPO, exiting..." "Red"
New-Item "$WorkingDir\logs\error.txt" -Value "Whitelist doesn't exist in GPO" -Force
Exit 1
}
$toUpdate = $toUpdate.Data
} }
else { else
$BlackList = $toSkip.GetUpperBound(0) {
if ($null -eq $BlackList) { if (Test-Path -Path "$WorkingDir\mods\*.ps1")
Write-ToLog "Critical: Blacklist doesn't exist in GPO, exiting..." "Red" {
New-Item "$WorkingDir\logs\error.txt" -Value "Blacklist doesn't exist in GPO" -Force Write-ToLog 'Mods are up to date.' 'Green'
Exit 1 }
} else
$toSkip = $toSkip.Data {
Write-ToLog 'No Mods are implemented...' 'Yellow'
}
} }
} if ($DeletedMods -gt 0)
{
#Get outdated Winget packages Write-ToLog "$DeletedMods Mods deleted (not externally managed) from local path: $($WAUConfig.InstallLocation.TrimEnd(' ', '\'))\mods" 'Red'
Write-ToLog "Checking application updates on Winget Repository..." "yellow"
$outdated = Get-WingetOutdatedApps
#If something unusual happened
if ($outdated -like "An unusual*") {
Write-ToLog "$outdated" "cyan"
$outdated = $False
}
#Run only if $outdated is populated!
if ($outdated) {
#Log list of app to update
foreach ($app in $outdated) {
#List available updates
$Log = "-> Available update : $($app.Name). Current version : $($app.Version). Available version : $($app.AvailableVersion)."
$Log | Write-host
$Log | out-file -filepath $LogFile -Append
} }
}
#Count good update installations #Test if _WAU-mods.ps1 exist: Mods for WAU (if Network is active/any Winget is installed/running as SYSTEM)
$Script:InstallOK = 0 $Mods = "$WorkingDir\mods"
if (Test-Path -Path "$Mods\_WAU-mods.ps1")
#Trick under user context when -BypassListForUsers is used {
if ($IsSystem -eq $false -and $WAUConfig.WAU_BypassListForUsers -eq 1) { Write-ToLog 'Running Mods for WAU...' 'Yellow'
Write-ToLog "Bypass system list in user context is Enabled." & "$Mods\_WAU-mods.ps1"
$UseWhiteList = $false $ModsExitCode = $LASTEXITCODE
$toSkip = $null #If _WAU-mods.ps1 has ExitCode 1 - Re-run WAU
if ($ModsExitCode -eq 1)
{
Write-ToLog 'Re-run WAU'
Start-Process -FilePath powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"$WorkingDir\winget-upgrade.ps1`""
exit
} }
}
#If White List }
if ($UseWhiteList) {
#For each app, notify and update if ($($WAUConfig.WAU_ListPath) -eq 'GPO')
foreach ($app in $outdated) { {
if (($toUpdate -contains $app.Id) -and $($app.Version) -ne "Unknown") { $Script:GPOList = $True
Update-App $app }
}
#if current app version is unknown #Get White or Black list
elseif ($($app.Version) -eq "Unknown") { if ($WAUConfig.WAU_UseWhiteList -eq 1)
Write-ToLog "$($app.Name) : Skipped upgrade because current version is 'Unknown'" "Gray" {
} Write-ToLog 'WAU uses White List config'
#if app is in "excluded list" $toUpdate = Get-IncludedApps
else { $UseWhiteList = $true
Write-ToLog "$($app.Name) : Skipped upgrade because it is not in the included app list" "Gray" }
} else
} {
Write-ToLog 'WAU uses Black List config'
$toSkip = Get-ExcludedApps
}
#Fix and count the array if GPO List as ERROR handling!
if ($GPOList)
{
if ($UseWhiteList)
{
$WhiteList = $toUpdate.GetUpperBound(0)
if ($null -eq $WhiteList)
{
Write-ToLog "Critical: Whitelist doesn't exist in GPO, exiting..." 'Red'
New-Item -Path "$WorkingDir\logs\error.txt" -Value "Whitelist doesn't exist in GPO" -Force
exit 1
} }
#If Black List or default $toUpdate = $toUpdate.Data
else { }
#For each app, notify and update else
foreach ($app in $outdated) { {
if (-not ($toSkip -contains $app.Id) -and $($app.Version) -ne "Unknown") { $BlackList = $toSkip.GetUpperBound(0)
Update-App $app if ($null -eq $BlackList)
} {
#if current app version is unknown Write-ToLog "Critical: Blacklist doesn't exist in GPO, exiting..." 'Red'
elseif ($($app.Version) -eq "Unknown") { New-Item -Path "$WorkingDir\logs\error.txt" -Value "Blacklist doesn't exist in GPO" -Force
Write-ToLog "$($app.Name) : Skipped upgrade because current version is 'Unknown'" "Gray" exit 1
}
#if app is in "excluded list"
else {
Write-ToLog "$($app.Name) : Skipped upgrade because it is in the excluded app list" "Gray"
}
}
} }
$toSkip = $toSkip.Data
}
}
if ($InstallOK -gt 0) { #Get outdated Winget packages
Write-ToLog "$InstallOK apps updated ! No more update." "Green" Write-ToLog 'Checking application updates on Winget Repository...' 'yellow'
$outdated = Get-WingetOutdatedApps
#If something unusual happened
if ($outdated -like 'An unusual*')
{
Write-ToLog "$outdated" 'cyan'
$outdated = $False
}
#Run only if $outdated is populated!
if ($outdated)
{
#Log list of app to update
foreach ($app in $outdated)
{
#List available updates
$Log = "-> Available update : $($app.Name). Current version : $($app.Version). Available version : $($app.AvailableVersion)."
$Log | Write-host
$Log | out-file -filepath $LogFile -Append
}
#Count good update installations
$Script:InstallOK = 0
#Trick under user context when -BypassListForUsers is used
if ($IsSystem -eq $false -and $WAUConfig.WAU_BypassListForUsers -eq 1)
{
Write-ToLog 'Bypass system list in user context is Enabled.'
$UseWhiteList = $false
$toSkip = $null
}
#If White List
if ($UseWhiteList)
{
#For each app, notify and update
foreach ($app in $outdated)
{
if (($toUpdate -contains $app.Id) -and $($app.Version) -ne 'Unknown')
{
Update-App $app
}
#if current app version is unknown
elseif ($($app.Version) -eq 'Unknown')
{
Write-ToLog "$($app.Name) : Skipped upgrade because current version is 'Unknown'" 'Gray'
}
#if app is in "excluded list"
else
{
Write-ToLog "$($app.Name) : Skipped upgrade because it is not in the included app list" 'Gray'
}
} }
} }
#If Black List or default
if ($InstallOK -eq 0 -or !$InstallOK) { else
Write-ToLog "No new update." "Green" {
} #For each app, notify and update
foreach ($app in $outdated)
#Check if any user is logged on if System and run User task (if installed) {
if ($IsSystem) { if (-not ($toSkip -contains $app.Id) -and $($app.Version) -ne 'Unknown')
#User check routine from: https://stackoverflow.com/questions/23219718/powershell-script-to-see-currently-logged-in-users-domain-and-machine-status {
$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue) Update-App $app
If ($explorerprocesses.Count -eq 0) { }
Write-ToLog "No explorer process found / Nobody interactively logged on..." #if current app version is unknown
elseif ($($app.Version) -eq 'Unknown')
{
Write-ToLog "$($app.Name) : Skipped upgrade because current version is 'Unknown'" 'Gray'
}
#if app is in "excluded list"
else
{
Write-ToLog "$($app.Name) : Skipped upgrade because it is in the excluded app list" 'Gray'
}
} }
Else { }
#Run WAU in user context if the user task exist
$UserScheduledTask = Get-ScheduledTask -TaskName "Winget-AutoUpdate-UserContext" -ErrorAction SilentlyContinue
if ($UserScheduledTask) {
#Get Winget system apps to excape them befor running user context if ($InstallOK -gt 0)
Write-ToLog "User logged on, get a list of installed Winget apps in System context..." {
Get-WingetSystemApps Write-ToLog "$InstallOK apps updated ! No more update." 'Green'
}
}
#Run user context scheduled task if ($InstallOK -eq 0 -or !$InstallOK)
Write-ToLog "Starting WAU in User context" {
Start-ScheduledTask $UserScheduledTask.TaskName -ErrorAction SilentlyContinue Write-ToLog 'No new update.' 'Green'
Exit 0 }
}
elseif (!$UserScheduledTask) { #Check if any user is logged on if System and run User task (if installed)
Write-ToLog "User context execution not installed..." if ($IsSystem)
} {
#User check routine from: https://stackoverflow.com/questions/23219718/powershell-script-to-see-currently-logged-in-users-domain-and-machine-status
$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
if ($explorerprocesses.Count -eq 0)
{
Write-ToLog 'No explorer process found / Nobody interactively logged on...'
}
else
{
#Run WAU in user context if the user task exist
$UserScheduledTask = Get-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -ErrorAction SilentlyContinue
if ($UserScheduledTask)
{
#Get Winget system apps to excape them befor running user context
Write-ToLog 'User logged on, get a list of installed Winget apps in System context...'
Get-WingetSystemApps
#Run user context scheduled task
Write-ToLog 'Starting WAU in User context'
Start-ScheduledTask -TaskName $UserScheduledTask.TaskName -ErrorAction SilentlyContinue
exit 0
} }
} elseif (!$UserScheduledTask)
} {
else { Write-ToLog 'User context execution not installed...'
Write-ToLog "Critical: Winget not installed or detected, exiting..." "red" }
New-Item "$WorkingDir\logs\error.txt" -Value "Winget not installed or detected" -Force }
Write-ToLog "End of process!" "Cyan" }
Exit 1 }
} else
{
Write-ToLog 'Critical: Winget not installed or detected, exiting...' 'red'
New-Item -Path "$WorkingDir\logs\error.txt" -Value 'Winget not installed or detected' -Force
Write-ToLog 'End of process!' 'Cyan'
exit 1
}
} }
#End #End
Write-ToLog "End of process!" "Cyan" Write-ToLog 'End of process!' 'Cyan'
Start-Sleep 3 Start-Sleep -Seconds 3

View File

@ -1,20 +1,40 @@
#Function to configure the prefered scope option as Machine # Function to configure the prefered scope option as Machine
function Add-ScopeMachine ($SettingsPath) { function Add-ScopeMachine
{
[CmdletBinding()]
param
(
[string]
$SettingsPath
)
if (Test-Path $SettingsPath) { if (Test-Path -Path $SettingsPath -ErrorAction SilentlyContinue)
$ConfigFile = Get-Content -Path $SettingsPath | Where-Object { $_ -notmatch '//' } | ConvertFrom-Json {
} $ConfigFile = (Get-Content -Path $SettingsPath -ErrorAction SilentlyContinue | Where-Object -FilterScript {
if (!$ConfigFile) { ($_ -notmatch '//')
$ConfigFile = @{} } | ConvertFrom-Json)
} }
if ($ConfigFile.installBehavior.preferences.scope) {
$ConfigFile.installBehavior.preferences.scope = "Machine"
}
else {
$Scope = New-Object PSObject -Property $(@{scope = "Machine" })
$Preference = New-Object PSObject -Property $(@{preferences = $Scope })
Add-Member -InputObject $ConfigFile -MemberType NoteProperty -Name 'installBehavior' -Value $Preference -Force
}
$ConfigFile | ConvertTo-Json | Out-File $SettingsPath -Encoding utf8 -Force
if (!$ConfigFile)
{
$ConfigFile = @{
}
}
if ($ConfigFile.installBehavior.preferences.scope)
{
$ConfigFile.installBehavior.preferences.scope = 'Machine'
}
else
{
$Scope = (New-Object -TypeName PSObject -Property $(@{
scope = 'Machine'
}))
$Preference = (New-Object -TypeName PSObject -Property $(@{
preferences = $Scope
}))
$null = (Add-Member -InputObject $ConfigFile -MemberType NoteProperty -Name 'installBehavior' -Value $Preference -Force)
}
$null = ($ConfigFile | ConvertTo-Json | Out-File -FilePath $SettingsPath -Encoding utf8 -Force -Confirm:$false)
} }

View File

@ -1,10 +1,26 @@
#Function to create shortcuts # Function to create shortcuts
function Add-Shortcut ($Target, $Shortcut, $Arguments, $Icon, $Description) { function Add-Shortcut
$WScriptShell = New-Object -ComObject WScript.Shell {
$Shortcut = $WScriptShell.CreateShortcut($Shortcut) [CmdletBinding()]
$Shortcut.TargetPath = $Target param
$Shortcut.Arguments = $Arguments (
$Shortcut.IconLocation = $Icon [string]
$Shortcut.Description = $Description $Target,
$Shortcut.Save() [string]
$Shortcut,
[string]
$Arguments,
[string]
$Icon,
[string]
$Description
)
$WScriptShell = (New-Object -ComObject WScript.Shell)
$Shortcut = $WScriptShell.CreateShortcut($Shortcut)
$Shortcut.TargetPath = $Target
$Shortcut.Arguments = $Arguments
$Shortcut.IconLocation = $Icon
$Shortcut.Description = $Description
$Shortcut.Save()
} }

View File

@ -1,27 +1,41 @@
Function Confirm-Installation ($AppName, $AppVer){ function Confirm-Installation
{
# Set json export file
#Set json export file [CmdletBinding()]
$JsonFile = "$WorkingDir\Config\InstalledApps.json" param
(
[string]
$AppName,
[string]
$AppVer
)
#Get installed apps and version in json file $JsonFile = ('{0}\Config\InstalledApps.json' -f $WorkingDir)
& $Winget export -s winget -o $JsonFile --include-versions | Out-Null
#Get json content # Get installed apps and version in json file
$Json = Get-Content $JsonFile -Raw | ConvertFrom-Json $null = (& $Winget export -s winget -o $JsonFile --include-versions)
#Get apps and version in hashtable # Get json content
$Packages = $Json.Sources.Packages $Json = (Get-Content -Path $JsonFile -Raw | ConvertFrom-Json)
#Remove json file # Get apps and version in hashtable
Remove-Item $JsonFile -Force $Packages = $Json.Sources.Packages
# Search for specific app and version # Remove json file
$Apps = $Packages | Where-Object { $_.PackageIdentifier -eq $AppName -and $_.Version -like "$AppVer*"} $null = (Remove-Item -Path $JsonFile -Force -Confirm:$false -ErrorAction SilentlyContinue)
if ($Apps){ # Search for specific app and version
return $true $Apps = $Packages | Where-Object -FilterScript {
} ($_.PackageIdentifier -eq $AppName -and $_.Version -like ('{0}*' -f $AppVer))
else{ }
return $false
} if ($Apps)
{
return $true
}
else
{
return $false
}
} }

View File

@ -1,50 +1,59 @@
#Function to get AZCopy, if it doesn't exist and update it, if it does # Function to get AZCopy, if it doesn't exist and update it, if it does
Function Get-AZCopy ($WingetUpdatePath) { function Get-AZCopy
{
[CmdletBinding()]
param
(
[string]
$WingetUpdatePath
)
$AZCopyLink = (Invoke-WebRequest -Uri https://aka.ms/downloadazcopy-v10-windows -UseBasicParsing -MaximumRedirection 0 -ErrorAction SilentlyContinue).headers.location $AZCopyLink = (Invoke-WebRequest -Uri https://aka.ms/downloadazcopy-v10-windows -UseBasicParsing -MaximumRedirection 0 -ErrorAction SilentlyContinue).headers.location
$AZCopyVersionRegex = [regex]::new("(\d+\.\d+\.\d+)") $AZCopyVersionRegex = [regex]::new('(\d+\.\d+\.\d+)')
$AZCopyLatestVersion = $AZCopyVersionRegex.Match($AZCopyLink).Value $AZCopyLatestVersion = $AZCopyVersionRegex.Match($AZCopyLink).Value
if ($null -eq $AZCopyLatestVersion -or "" -eq $AZCopyLatestVersion) { if ($null -eq $AZCopyLatestVersion -or '' -eq $AZCopyLatestVersion)
$AZCopyLatestVersion = "0.0.0" {
} $AZCopyLatestVersion = '0.0.0'
}
if (Test-Path -Path "$WingetUpdatePath\azcopy.exe" -PathType Leaf) { if (Test-Path -Path ('{0}\azcopy.exe' -f $WingetUpdatePath) -PathType Leaf -ErrorAction SilentlyContinue)
$AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v {
$AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value $AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v
Write-ToLog "AZCopy version $AZCopyCurrentVersion found" $AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value
} Write-ToLog -LogMsg ('AZCopy version {0} found' -f $AZCopyCurrentVersion)
else { }
Write-ToLog "AZCopy not already installed" else
$AZCopyCurrentVersion = "0.0.0" {
} Write-ToLog -LogMsg 'AZCopy not already installed'
$AZCopyCurrentVersion = '0.0.0'
}
if (([version] $AZCopyCurrentVersion) -lt ([version] $AZCopyLatestVersion)) { if (([version]$AZCopyCurrentVersion) -lt ([version]$AZCopyLatestVersion))
Write-ToLog "Installing version $AZCopyLatestVersion of AZCopy" {
Invoke-WebRequest -Uri $AZCopyLink -UseBasicParsing -OutFile "$WingetUpdatePath\azcopyv10.zip" Write-ToLog -LogMsg ('Installing version {0} of AZCopy' -f $AZCopyLatestVersion)
Write-ToLog "Extracting AZCopy zip file" $null = (Invoke-WebRequest -Uri $AZCopyLink -UseBasicParsing -OutFile ('{0}\azcopyv10.zip' -f $WingetUpdatePath))
Write-ToLog -LogMsg 'Extracting AZCopy zip file'
$null = (Expand-Archive -Path ('{0}\azcopyv10.zip' -f $WingetUpdatePath) -DestinationPath $WingetUpdatePath -Force -Confirm:$false)
$AZCopyPathSearch = (Resolve-Path -Path ('{0}\azcopy_*' -f $WingetUpdatePath))
Expand-archive -Path "$WingetUpdatePath\azcopyv10.zip" -Destinationpath "$WingetUpdatePath" -Force if ($AZCopyPathSearch -is [array])
{
$AZCopyEXEPath = $AZCopyPathSearch[$AZCopyPathSearch.Length - 1]
}
else
{
$AZCopyEXEPath = $AZCopyPathSearch
}
$AZCopyPathSearch = Resolve-Path -path "$WingetUpdatePath\azcopy_*" Write-ToLog -LogMsg "Copying 'azcopy.exe' to main folder"
$null = (Copy-Item -Path ('{0}\azcopy.exe' -f $AZCopyEXEPath) -Destination ('{0}\' -f $WingetUpdatePath) -Force -Confirm:$false)
if ($AZCopyPathSearch -is [array]) { Write-ToLog -LogMsg 'Removing temporary AZCopy files'
$AZCopyEXEPath = $AZCopyPathSearch[$AZCopyPathSearch.Length - 1] $null = (Remove-Item -Path $AZCopyEXEPath -Recurse -Force -Confirm:$false)
} $null = (Remove-Item -Path ('{0}\azcopyv10.zip' -f $WingetUpdatePath) -Force -Confirm:$false)
else { $AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v
$AZCopyEXEPath = $AZCopyPathSearch $AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value
} Write-ToLog -LogMsg ('AZCopy version {0} installed' -f $AZCopyCurrentVersion)
}
Write-ToLog "Copying 'azcopy.exe' to main folder"
Copy-Item "$AZCopyEXEPath\azcopy.exe" -Destination "$WingetUpdatePath\"
Write-ToLog "Removing temporary AZCopy files"
Remove-Item -Path $AZCopyEXEPath -Recurse
Remove-Item -Path "$WingetUpdatePath\azcopyv10.zip"
$AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v
$AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value
Write-ToLog "AZCopy version $AZCopyCurrentVersion installed"
}
} }

View File

@ -1,12 +1,19 @@
#Get the winget App Information # Get the winget App Information
Function Get-AppInfo ($AppID) { function Get-AppInfo
#Get AppID Info {
$String = & $winget show $AppID --accept-source-agreements -s winget | Out-String # Get AppID Info
[CmdletBinding()]
param
(
[string]
$AppID
)
#Search for Release Note info $String = (& $winget show $AppID --accept-source-agreements -s winget | Out-String)
$ReleaseNote = [regex]::match($String, "(?<=Release Notes Url: )(.*)(?=\n)").Groups[0].Value # Search for Release Note info
$ReleaseNote = [regex]::match($String, '(?<=Release Notes Url: )(.*)(?=\n)').Groups[0].Value
#Return Release Note # Return Release Note
return $ReleaseNote return $ReleaseNote
} }

View File

@ -1,31 +1,31 @@
#Function to get the Block List apps #Function to get the Block List apps
function Get-ExcludedApps { function Get-ExcludedApps
{
if ($GPOList)
{
if (Test-Path -Path 'HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList' -ErrorAction SilentlyContinue)
{
$Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList\'
if ($GPOList) { $ValueNames = (Get-Item -Path 'HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList').Property
if (Test-Path "HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList") { foreach ($ValueName in $ValueNames)
{
$Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList\' $AppIDs = [Microsoft.Win32.Registry]::GetValue($Key, $ValueName, $false)
[PSCustomObject]@{
$ValueNames = (Get-Item -Path "HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList").Property Value = $ValueName
Data = $AppIDs.Trim()
foreach ($ValueName in $ValueNames) {
$AppIDs = [Microsoft.Win32.Registry]::GetValue($Key, $ValueName, $false)
[PSCustomObject]@{
Value = $ValueName
Data = $AppIDs.Trim()
}
} }
}
}
} return $AppIDs
return $AppIDs }
elseif (Test-Path -Path ('{0}\excluded_apps.txt' -f $WorkingDir) -ErrorAction SilentlyContinue)
} {
elseif (Test-Path "$WorkingDir\excluded_apps.txt") { return (Get-Content -Path ('{0}\excluded_apps.txt' -f $WorkingDir)).Trim() | Where-Object -FilterScript {
$_.length -gt 0
return (Get-Content -Path "$WorkingDir\excluded_apps.txt").Trim() | Where-Object { $_.length -gt 0 } }
}
}
} }

View File

@ -1,31 +1,30 @@
#Function to get the allow List apps # Function to get the allow List apps
function Get-IncludedApps { function Get-IncludedApps
{
if ($GPOList)
{
if (Test-Path -Path 'HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\WhiteList' -ErrorAction SilentlyContinue)
{
$Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\WhiteList\'
$ValueNames = (Get-Item -Path 'HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\WhiteList').Property
if ($GPOList) { foreach ($ValueName in $ValueNames)
{
if (Test-Path "HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\WhiteList") { $AppIDs = [Microsoft.Win32.Registry]::GetValue($Key, $ValueName, $false)
[PSCustomObject]@{
$Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\WhiteList\' Value = $ValueName
Data = $AppIDs.Trim()
$ValueNames = (Get-Item -Path "HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\WhiteList").Property
foreach ($ValueName in $ValueNames) {
$AppIDs = [Microsoft.Win32.Registry]::GetValue($Key, $ValueName, $false)
[PSCustomObject]@{
Value = $ValueName
Data = $AppIDs.Trim()
}
} }
}
}
} return $AppIDs
return $AppIDs }
elseif (Test-Path -Path ('{0}\included_apps.txt' -f $WorkingDir) -ErrorAction SilentlyContinue)
} {
elseif (Test-Path "$WorkingDir\included_apps.txt") { return (Get-Content -Path ('{0}\included_apps.txt' -f $WorkingDir)).Trim() | Where-Object -FilterScript {
$_.length -gt 0
return (Get-Content -Path "$WorkingDir\included_apps.txt").Trim() | Where-Object { $_.length -gt 0 } }
}
}
} }

View File

@ -1,28 +1,31 @@
#Function to get the locale file for notifications #Function to get the locale file for notifications
Function Get-NotifLocale { function Get-NotifLocale
{
#Get OS locale # Get OS locale
$OSLocale = (Get-UICulture).Parent $OSLocale = (Get-UICulture).Parent
#Test if OS locale notif file exists # Test if OS locale notif file exists
$TestOSLocalPath = "$WorkingDir\locale\$($OSLocale.Name).xml" $TestOSLocalPath = ('{0}\locale\{1}.xml' -f $WorkingDir, $OSLocale.Name)
#Set OS Local if file exists # Set OS Local if file exists
if (Test-Path $TestOSLocalPath) { if (Test-Path -Path $TestOSLocalPath -ErrorAction SilentlyContinue)
$LocaleDisplayName = $OSLocale.DisplayName {
$LocaleFile = $TestOSLocalPath $LocaleDisplayName = $OSLocale.DisplayName
} $LocaleFile = $TestOSLocalPath
#Set English if file doesn't exist }
else { else
$LocaleDisplayName = "English" {
$LocaleFile = "$WorkingDir\locale\en.xml" # Set English if file doesn't exist
} $LocaleDisplayName = 'English'
$LocaleFile = ('{0}\locale\en.xml' -f $WorkingDir)
}
#Get locale XML file content # Get locale XML file content
[xml]$Script:NotifLocale = Get-Content $LocaleFile -Encoding UTF8 -ErrorAction SilentlyContinue [xml]$Script:NotifLocale = (Get-Content -Path $LocaleFile -Encoding UTF8 -ErrorAction SilentlyContinue)
#Rerturn langague display name # Rerturn langague display name
Return $LocaleDisplayName return $LocaleDisplayName
} }

View File

@ -1,364 +1,471 @@
#Function to get the Domain/Local Policies (GPO) # Function to get the Domain/Local Policies (GPO)
Function Get-Policies { function Get-Policies
#Get WAU Policies and set the Configurations Registry Accordingly {
$WAUPolicies = Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate" -ErrorAction SilentlyContinue # Get WAU Policies and set the Configurations Registry Accordingly
if ($WAUPolicies) { $WAUPolicies = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate' -ErrorAction SilentlyContinue)
if ($($WAUPolicies.WAU_ActivateGPOManagement -eq 1)) {
$ChangedSettings = 0 if ($WAUPolicies)
$regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" {
if ($null -ne $($WAUPolicies.WAU_BypassListForUsers) -and ($($WAUPolicies.WAU_BypassListForUsers) -ne $($WAUConfig.WAU_BypassListForUsers))) { if ($($WAUPolicies.WAU_ActivateGPOManagement -eq 1))
New-ItemProperty $regPath -Name WAU_BypassListForUsers -Value $($WAUPolicies.WAU_BypassListForUsers) -PropertyType DWord -Force | Out-Null {
$ChangedSettings++ $ChangedSettings = 0
$regPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate'
if ($null -ne $($WAUPolicies.WAU_BypassListForUsers) -and ($($WAUPolicies.WAU_BypassListForUsers) -ne $($WAUConfig.WAU_BypassListForUsers)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_BypassListForUsers -Value $($WAUPolicies.WAU_BypassListForUsers) -PropertyType DWord -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_BypassListForUsers) -and ($($WAUConfig.WAU_BypassListForUsers) -or $($WAUConfig.WAU_BypassListForUsers) -eq 0))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_BypassListForUsers -Force -ErrorAction SilentlyContinue -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_DisableAutoUpdate) -and ($($WAUPolicies.WAU_DisableAutoUpdate) -ne $($WAUConfig.WAU_DisableAutoUpdate)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_DisableAutoUpdate -Value $($WAUPolicies.WAU_DisableAutoUpdate) -PropertyType DWord -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_DisableAutoUpdate) -and ($($WAUConfig.WAU_DisableAutoUpdate) -or $($WAUConfig.WAU_DisableAutoUpdate) -eq 0))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_DisableAutoUpdate -Force -ErrorAction SilentlyContinue -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_DoNotRunOnMetered) -and ($($WAUPolicies.WAU_DoNotRunOnMetered) -ne $($WAUConfig.WAU_DoNotRunOnMetered)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_DoNotRunOnMetered -Value $($WAUPolicies.WAU_DoNotRunOnMetered) -PropertyType DWord -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_DoNotRunOnMetered) -and !$($WAUConfig.WAU_DoNotRunOnMetered))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_DoNotRunOnMetered -Value 1 -PropertyType DWord -Force -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UpdatePrerelease) -and ($($WAUPolicies.WAU_UpdatePrerelease) -ne $($WAUConfig.WAU_UpdatePrerelease)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatePrerelease -Value $($WAUPolicies.WAU_UpdatePrerelease) -PropertyType DWord -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_UpdatePrerelease) -and $($WAUConfig.WAU_UpdatePrerelease))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatePrerelease -Value 0 -PropertyType DWord -Force -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UseWhiteList) -and ($($WAUPolicies.WAU_UseWhiteList) -ne $($WAUConfig.WAU_UseWhiteList)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UseWhiteList -Value $($WAUPolicies.WAU_UseWhiteList) -PropertyType DWord -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_UseWhiteList) -and ($($WAUConfig.WAU_UseWhiteList) -or $($WAUConfig.WAU_UseWhiteList) -eq 0))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_UseWhiteList -Force -ErrorAction SilentlyContinue -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_ListPath) -and ($($WAUPolicies.WAU_ListPath) -ne $($WAUConfig.WAU_ListPath)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_ListPath -Value $($WAUPolicies.WAU_ListPath.TrimEnd(' ', '\', '/')) -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_ListPath) -and $($WAUConfig.WAU_ListPath))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_ListPath -Force -ErrorAction SilentlyContinue -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_ModsPath) -and ($($WAUPolicies.WAU_ModsPath) -ne $($WAUConfig.WAU_ModsPath)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_ModsPath -Value $($WAUPolicies.WAU_ModsPath.TrimEnd(' ', '\', '/')) -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_ModsPath) -and $($WAUConfig.WAU_ModsPath))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_ModsPath -Force -ErrorAction SilentlyContinue -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_AzureBlobSASURL) -and ($($WAUPolicies.WAU_AzureBlobSASURL) -ne $($WAUConfig.WAU_AzureBlobSASURL)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_AzureBlobSASURL -Value $($WAUPolicies.WAU_AzureBlobSASURL.TrimEnd(' ', '\', '/')) -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_AzureBlobSASURL) -and $($WAUConfig.WAU_AzureBlobSASURL))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_AzureBlobSASURL -Force -ErrorAction SilentlyContinue -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_NotificationLevel) -and ($($WAUPolicies.WAU_NotificationLevel) -ne $($WAUConfig.WAU_NotificationLevel)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_NotificationLevel -Value $($WAUPolicies.WAU_NotificationLevel) -Force -Confirm:$false)
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_NotificationLevel) -and $($WAUConfig.WAU_NotificationLevel) -ne 'Full')
{
$null = (New-ItemProperty -Path $regPath -Name WAU_NotificationLevel -Value 'Full' -Force -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UpdatesAtTime) -and ($($WAUPolicies.WAU_UpdatesAtTime) -ne $($WAUConfig.WAU_UpdatesAtTime)))
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesAtTime -Value $($WAUPolicies.WAU_UpdatesAtTime) -Force -Confirm:$false)
$Script:WAUConfig = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate')
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++)
{
if (($definition.Triggers.Item($triggerId).Type -eq '2') -or ($definition.Triggers.Item($triggerId).Type -eq '3'))
{
$PreStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(0, 11)
$PostStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(19, 6)
$Boundary = $PreStartBoundary + $($WAUPolicies.WAU_UpdatesAtTime) + $PostStartBoundary
$definition.Triggers.Item($triggerId).StartBoundary = $Boundary
break
}
} }
elseif ($null -eq $($WAUPolicies.WAU_BypassListForUsers) -and ($($WAUConfig.WAU_BypassListForUsers) -or $($WAUConfig.WAU_BypassListForUsers) -eq 0)) { $null = $folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null)
Remove-ItemProperty $regPath -Name WAU_BypassListForUsers -Force -ErrorAction SilentlyContinue | Out-Null $ChangedSettings++
$ChangedSettings++ }
elseif ($null -eq $($WAUPolicies.WAU_UpdatesAtTime) -and $($WAUConfig.WAU_UpdatesAtTime) -ne '06:00:00')
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesAtTime -Value '06:00:00' -Force -Confirm:$false)
$Script:WAUConfig = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate'
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++)
{
if (($definition.Triggers.Item($triggerId).Type -eq '2') -or ($definition.Triggers.Item($triggerId).Type -eq '3'))
{
$PreStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(0, 11)
$PostStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(19, 6)
$Boundary = $PreStartBoundary + '06:00:00' + $PostStartBoundary
$definition.Triggers.Item($triggerId).StartBoundary = $Boundary
break
}
} }
if ($null -ne $($WAUPolicies.WAU_DisableAutoUpdate) -and ($($WAUPolicies.WAU_DisableAutoUpdate) -ne $($WAUConfig.WAU_DisableAutoUpdate))) { $null = $folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null)
New-ItemProperty $regPath -Name WAU_DisableAutoUpdate -Value $($WAUPolicies.WAU_DisableAutoUpdate) -PropertyType DWord -Force | Out-Null $ChangedSettings++
$ChangedSettings++ }
}
elseif ($null -eq $($WAUPolicies.WAU_DisableAutoUpdate) -and ($($WAUConfig.WAU_DisableAutoUpdate) -or $($WAUConfig.WAU_DisableAutoUpdate) -eq 0)) { if ($null -ne $($WAUPolicies.WAU_UpdatesInterval) -and ($($WAUPolicies.WAU_UpdatesInterval) -ne $($WAUConfig.WAU_UpdatesInterval)))
Remove-ItemProperty $regPath -Name WAU_DisableAutoUpdate -Force -ErrorAction SilentlyContinue | Out-Null {
$ChangedSettings++ $null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesInterval -Value $($WAUPolicies.WAU_UpdatesInterval) -Force -Confirm:$false)
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++)
{
if (($definition.Triggers.Item($triggerId).Type -eq '2') -or ($definition.Triggers.Item($triggerId).Type -eq '3'))
{
$UpdatesAtTime = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(11, 8)
$definition.Triggers.Remove($triggerId)
$triggerId -= 1
}
} }
if ($null -ne $($WAUPolicies.WAU_DoNotRunOnMetered) -and ($($WAUPolicies.WAU_DoNotRunOnMetered) -ne $($WAUConfig.WAU_DoNotRunOnMetered))) { $null = $folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null)
New-ItemProperty $regPath -Name WAU_DoNotRunOnMetered -Value $($WAUPolicies.WAU_DoNotRunOnMetered) -PropertyType DWord -Force | Out-Null
$ChangedSettings++ if (!$($WAUConfig.WAU_UpdatesAtTime))
} {
elseif ($null -eq $($WAUPolicies.WAU_DoNotRunOnMetered) -and !$($WAUConfig.WAU_DoNotRunOnMetered)) { $null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesAtTime -Value $UpdatesAtTime -Force -Confirm:$false)
New-ItemProperty $regPath -Name WAU_DoNotRunOnMetered -Value 1 -PropertyType DWord -Force | Out-Null $Script:WAUConfig = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate')
$ChangedSettings++
} }
if ($null -ne $($WAUPolicies.WAU_UpdatePrerelease) -and ($($WAUPolicies.WAU_UpdatePrerelease) -ne $($WAUConfig.WAU_UpdatePrerelease))) { if ($($WAUPolicies.WAU_UpdatesInterval) -ne 'Never')
New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value $($WAUPolicies.WAU_UpdatePrerelease) -PropertyType DWord -Force | Out-Null {
$ChangedSettings++ #Count Triggers (correctly)
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
$null = $definition.Triggers.Count
switch ($($WAUPolicies.WAU_UpdatesInterval))
{
'Daily'
{
$tasktrigger = New-ScheduledTaskTrigger -Daily -At $($WAUConfig.WAU_UpdatesAtTime)
break
}
'BiDaily'
{
$tasktrigger = New-ScheduledTaskTrigger -Daily -At $($WAUConfig.WAU_UpdatesAtTime) -DaysInterval 2
break
}
'Weekly'
{
$tasktrigger = New-ScheduledTaskTrigger -Weekly -At $($WAUConfig.WAU_UpdatesAtTime) -DaysOfWeek 2
break
}
'BiWeekly'
{
$tasktrigger = New-ScheduledTaskTrigger -Weekly -At $($WAUConfig.WAU_UpdatesAtTime) -DaysOfWeek 2 -WeeksInterval 2
break
}
'Monthly'
{
$tasktrigger = New-ScheduledTaskTrigger -Weekly -At $($WAUConfig.WAU_UpdatesAtTime) -DaysOfWeek 2 -WeeksInterval 4
break
}
}
if ($definition.Triggers.Count -gt 0)
{
$triggers = @()
$triggers += (Get-ScheduledTask -TaskName 'Winget-AutoUpdate').Triggers
$triggers += $tasktrigger
$null = (Set-ScheduledTask -TaskName 'Winget-AutoUpdate' -Trigger $triggers)
}
else
{
$null = (Set-ScheduledTask -TaskName 'Winget-AutoUpdate' -Trigger $tasktrigger)
}
} }
elseif ($null -eq $($WAUPolicies.WAU_UpdatePrerelease) -and $($WAUConfig.WAU_UpdatePrerelease)) { $ChangedSettings++
New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value 0 -PropertyType DWord -Force | Out-Null }
$ChangedSettings++ elseif ($null -eq $($WAUPolicies.WAU_UpdatesInterval) -and $($WAUConfig.WAU_UpdatesInterval) -ne 'Daily')
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesInterval -Value 'Daily' -Force -Confirm:$false)
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++)
{
if (($definition.Triggers.Item($triggerId).Type -eq '2') -or ($definition.Triggers.Item($triggerId).Type -eq '3'))
{
$UpdatesAtTime = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(11, 8)
$definition.Triggers.Remove($triggerId)
$triggerId -= 1
}
} }
if ($null -ne $($WAUPolicies.WAU_UseWhiteList) -and ($($WAUPolicies.WAU_UseWhiteList) -ne $($WAUConfig.WAU_UseWhiteList))) { $null = $folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null)
New-ItemProperty $regPath -Name WAU_UseWhiteList -Value $($WAUPolicies.WAU_UseWhiteList) -PropertyType DWord -Force | Out-Null
$ChangedSettings++ if (!$($WAUConfig.WAU_UpdatesAtTime))
} {
elseif ($null -eq $($WAUPolicies.WAU_UseWhiteList) -and ($($WAUConfig.WAU_UseWhiteList) -or $($WAUConfig.WAU_UseWhiteList) -eq 0)) { $null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesAtTime -Value $UpdatesAtTime -Force -Confirm:$false)
Remove-ItemProperty $regPath -Name WAU_UseWhiteList -Force -ErrorAction SilentlyContinue | Out-Null $Script:WAUConfig = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate')
$ChangedSettings++
} }
if ($null -ne $($WAUPolicies.WAU_ListPath) -and ($($WAUPolicies.WAU_ListPath) -ne $($WAUConfig.WAU_ListPath))) { $tasktrigger = (New-ScheduledTaskTrigger -Daily -At $($WAUConfig.WAU_UpdatesAtTime))
New-ItemProperty $regPath -Name WAU_ListPath -Value $($WAUPolicies.WAU_ListPath.TrimEnd(" ", "\", "/")) -Force | Out-Null
$ChangedSettings++ # Count Triggers (correctly)
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
$null = $definition.Triggers.Count
if ($definition.Triggers.Count -gt 0)
{
$triggers = @()
$triggers += (Get-ScheduledTask -TaskName 'Winget-AutoUpdate').Triggers
$triggers += $tasktrigger
$null = (Set-ScheduledTask -TaskName 'Winget-AutoUpdate' -Trigger $triggers)
} }
elseif ($null -eq $($WAUPolicies.WAU_ListPath) -and $($WAUConfig.WAU_ListPath)) { else
Remove-ItemProperty $regPath -Name WAU_ListPath -Force -ErrorAction SilentlyContinue | Out-Null {
$ChangedSettings++ $null = (Set-ScheduledTask -TaskName 'Winget-AutoUpdate' -Trigger $tasktrigger)
}
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UpdatesAtLogon) -and ($($WAUPolicies.WAU_UpdatesAtLogon) -ne $($WAUConfig.WAU_UpdatesAtLogon)))
{
if ($WAUPolicies.WAU_UpdatesAtLogon -eq 1)
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesAtLogon -Value $($WAUPolicies.WAU_UpdatesAtLogon) -PropertyType DWord -Force -Confirm:$false)
$triggers = @()
$triggers += (Get-ScheduledTask -TaskName 'Winget-AutoUpdate').Triggers
# Count Triggers (correctly)
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
$triggerLogon = $false
foreach ($trigger in $definition.Triggers)
{
if ($trigger.Type -eq '9')
{
$triggerLogon = $true
break
}
}
if (!$triggerLogon)
{
$triggers += New-ScheduledTaskTrigger -AtLogOn
$null = (Set-ScheduledTask -TaskName 'Winget-AutoUpdate' -Trigger $triggers)
}
}
else
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatesAtLogon -Value $($WAUPolicies.WAU_UpdatesAtLogon) -PropertyType DWord -Force -Confirm:$false)
$service = (New-Object -ComObject Schedule.Service)
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask('Winget-AutoUpdate')
$definition = $task.Definition
$null = $definition.Triggers.Count
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++)
{
if ($definition.Triggers.Item($triggerId).Type -eq '9')
{
$definition.Triggers.Remove($triggerId)
$triggerId -= 1
}
}
$null = $folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null)
} }
if ($null -ne $($WAUPolicies.WAU_ModsPath) -and ($($WAUPolicies.WAU_ModsPath) -ne $($WAUConfig.WAU_ModsPath))) { $ChangedSettings++
New-ItemProperty $regPath -Name WAU_ModsPath -Value $($WAUPolicies.WAU_ModsPath.TrimEnd(" ", "\", "/")) -Force | Out-Null }
$ChangedSettings++ elseif ($null -eq $($WAUPolicies.WAU_UpdatesAtLogon) -and ($($WAUConfig.WAU_UpdatesAtLogon) -or $($WAUConfig.WAU_UpdatesAtLogon) -eq 0))
} {
elseif ($null -eq $($WAUPolicies.WAU_ModsPath) -and $($WAUConfig.WAU_ModsPath)) { $null = (Remove-ItemProperty -Path $regPath -Name WAU_UpdatesAtLogon -Force -ErrorAction SilentlyContinue -Confirm:$false)
Remove-ItemProperty $regPath -Name WAU_ModsPath -Force -ErrorAction SilentlyContinue | Out-Null $service = (New-Object -ComObject Schedule.Service)
$ChangedSettings++ $service.Connect($env:COMPUTERNAME)
} $folder = $service.GetFolder('\')
if ($null -ne $($WAUPolicies.WAU_AzureBlobSASURL) -and ($($WAUPolicies.WAU_AzureBlobSASURL) -ne $($WAUConfig.WAU_AzureBlobSASURL))) { $task = $folder.GetTask('Winget-AutoUpdate')
New-ItemProperty $regPath -Name WAU_AzureBlobSASURL -Value $($WAUPolicies.WAU_AzureBlobSASURL.TrimEnd(" ", "\", "/")) -Force | Out-Null $definition = $task.Definition
$ChangedSettings++
} for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++)
elseif ($null -eq $($WAUPolicies.WAU_AzureBlobSASURL) -and $($WAUConfig.WAU_AzureBlobSASURL)) { {
Remove-ItemProperty $regPath -Name WAU_AzureBlobSASURL -Force -ErrorAction SilentlyContinue | Out-Null if ($definition.Triggers.Item($triggerId).Type -eq '9')
$ChangedSettings++ {
$definition.Triggers.Remove($triggerId)
$triggerId -= 1
}
} }
if ($null -ne $($WAUPolicies.WAU_NotificationLevel) -and ($($WAUPolicies.WAU_NotificationLevel) -ne $($WAUConfig.WAU_NotificationLevel))) { $null = $folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null)
New-ItemProperty $regPath -Name WAU_NotificationLevel -Value $($WAUPolicies.WAU_NotificationLevel) -Force | Out-Null $ChangedSettings++
$ChangedSettings++ }
}
elseif ($null -eq $($WAUPolicies.WAU_NotificationLevel) -and $($WAUConfig.WAU_NotificationLevel) -ne "Full") {
New-ItemProperty $regPath -Name WAU_NotificationLevel -Value "Full" -Force | Out-Null
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UpdatesAtTime) -and ($($WAUPolicies.WAU_UpdatesAtTime) -ne $($WAUConfig.WAU_UpdatesAtTime))) { if ($null -ne $($WAUPolicies.WAU_UserContext) -and ($($WAUPolicies.WAU_UserContext) -ne $($WAUConfig.WAU_UserContext)))
New-ItemProperty $regPath -Name WAU_UpdatesAtTime -Value $($WAUPolicies.WAU_UpdatesAtTime) -Force | Out-Null {
$Script:WAUConfig = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" $null = (New-ItemProperty -Path $regPath -Name WAU_UserContext -Value $($WAUPolicies.WAU_UserContext) -PropertyType DWord -Force -Confirm:$false)
$service = New-Object -ComObject Schedule.Service
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask("Winget-AutoUpdate")
$definition = $task.Definition
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++) {
if (($definition.Triggers.Item($triggerId).Type -eq "2") -or ($definition.Triggers.Item($triggerId).Type -eq "3")) {
$PreStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(0, 11)
$PostStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(19, 6)
$Boundary = $PreStartBoundary + $($WAUPolicies.WAU_UpdatesAtTime) + $PostStartBoundary
$definition.Triggers.Item($triggerId).StartBoundary = $Boundary
break
$triggerId -= 1
}
}
$folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null) | Out-Null
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_UpdatesAtTime) -and $($WAUConfig.WAU_UpdatesAtTime) -ne "06:00:00") {
New-ItemProperty $regPath -Name WAU_UpdatesAtTime -Value "06:00:00" -Force | Out-Null
$Script:WAUConfig = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate"
$service = New-Object -ComObject Schedule.Service
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask("Winget-AutoUpdate")
$definition = $task.Definition
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++) {
if (($definition.Triggers.Item($triggerId).Type -eq "2") -or ($definition.Triggers.Item($triggerId).Type -eq "3")) {
$PreStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(0, 11)
$PostStartBoundary = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(19, 6)
$Boundary = $PreStartBoundary + "06:00:00" + $PostStartBoundary
$definition.Triggers.Item($triggerId).StartBoundary = $Boundary
break
$triggerId -= 1
}
}
$folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null) | Out-Null
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UpdatesInterval) -and ($($WAUPolicies.WAU_UpdatesInterval) -ne $($WAUConfig.WAU_UpdatesInterval))) { if ($WAUPolicies.WAU_UserContext -eq 1)
New-ItemProperty $regPath -Name WAU_UpdatesInterval -Value $($WAUPolicies.WAU_UpdatesInterval) -Force | Out-Null {
$service = New-Object -ComObject Schedule.Service # Settings for the scheduled task in User context
$service.Connect($env:COMPUTERNAME) $taskAction = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\winget-upgrade.ps1`"`""
$folder = $service.GetFolder('\') $taskUserPrincipal = New-ScheduledTaskPrincipal -GroupId S-1-5-11
$task = $folder.GetTask("Winget-AutoUpdate") $taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 03:00:00
$definition = $task.Definition # Set up the task for user apps
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++) { $task = (New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings)
if (($definition.Triggers.Item($triggerId).Type -eq "2") -or ($definition.Triggers.Item($triggerId).Type -eq "3")) { $null = (Register-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -InputObject $task -Force)
$UpdatesAtTime = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(11, 8) }
$definition.Triggers.Remove($triggerId) else
$triggerId -= 1 {
} $null = (Get-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false -ErrorAction SilentlyContinue)
} }
$folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null) | Out-Null $ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_UserContext) -and ($($WAUConfig.WAU_UserContext) -or $($WAUConfig.WAU_UserContext) -eq 0))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_UserContext -Force -ErrorAction SilentlyContinue -Confirm:$false)
$null = (Get-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false -ErrorAction SilentlyContinue)
$ChangedSettings++
}
if (!$($WAUConfig.WAU_UpdatesAtTime)) { if ($null -ne $($WAUPolicies.WAU_DesktopShortcut) -and ($($WAUPolicies.WAU_DesktopShortcut) -ne $($WAUConfig.WAU_DesktopShortcut)))
New-ItemProperty $regPath -Name WAU_UpdatesAtTime -Value $UpdatesAtTime -Force | Out-Null {
$Script:WAUConfig = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" $null = (New-ItemProperty -Path $regPath -Name WAU_DesktopShortcut -Value $($WAUPolicies.WAU_DesktopShortcut) -PropertyType DWord -Force -Confirm:$false)
}
if ($($WAUPolicies.WAU_UpdatesInterval) -ne "Never") { if ($WAUPolicies.WAU_DesktopShortcut -eq 1)
#Count Triggers (correctly) {
$service = New-Object -ComObject Schedule.Service Add-Shortcut 'wscript.exe' "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`"`"" "${env:SystemRoot}\System32\shell32.dll,-16739" 'Manual start of Winget-AutoUpdate (WAU)...'
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask("Winget-AutoUpdate")
$definition = $task.Definition
$definition.Triggers.Count | Out-Null
switch ($($WAUPolicies.WAU_UpdatesInterval)) {
"Daily" { $tasktrigger = New-ScheduledTaskTrigger -Daily -At $($WAUConfig.WAU_UpdatesAtTime); break }
"BiDaily" { $tasktrigger = New-ScheduledTaskTrigger -Daily -At $($WAUConfig.WAU_UpdatesAtTime) -DaysInterval 2; break }
"Weekly" { $tasktrigger = New-ScheduledTaskTrigger -Weekly -At $($WAUConfig.WAU_UpdatesAtTime) -DaysOfWeek 2; break }
"BiWeekly" { $tasktrigger = New-ScheduledTaskTrigger -Weekly -At $($WAUConfig.WAU_UpdatesAtTime) -DaysOfWeek 2 -WeeksInterval 2; break }
"Monthly" { $tasktrigger = New-ScheduledTaskTrigger -Weekly -At $($WAUConfig.WAU_UpdatesAtTime) -DaysOfWeek 2 -WeeksInterval 4; break }
}
if ($definition.Triggers.Count -gt 0) {
$triggers = @()
$triggers += (Get-ScheduledTask "Winget-AutoUpdate").Triggers
$triggers += $tasktrigger
Set-ScheduledTask -TaskName "Winget-AutoUpdate" -Trigger $triggers
}
else {
Set-ScheduledTask -TaskName "Winget-AutoUpdate" -Trigger $tasktrigger
}
}
$ChangedSettings++
} }
elseif ($null -eq $($WAUPolicies.WAU_UpdatesInterval) -and $($WAUConfig.WAU_UpdatesInterval) -ne "Daily") { else
New-ItemProperty $regPath -Name WAU_UpdatesInterval -Value "Daily" -Force | Out-Null {
$service = New-Object -ComObject Schedule.Service $null = (Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force -Confirm:$false)
$service.Connect($env:COMPUTERNAME) }
$folder = $service.GetFolder('\') $ChangedSettings++
$task = $folder.GetTask("Winget-AutoUpdate") }
$definition = $task.Definition elseif ($null -eq $($WAUPolicies.WAU_DesktopShortcut) -and ($($WAUConfig.WAU_DesktopShortcut) -or $($WAUConfig.WAU_DesktopShortcut) -eq 0))
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++) { {
if (($definition.Triggers.Item($triggerId).Type -eq "2") -or ($definition.Triggers.Item($triggerId).Type -eq "3")) { $null = (Remove-ItemProperty -Path $regPath -Name WAU_DesktopShortcut -Force -Confirm:$false -ErrorAction SilentlyContinue)
$UpdatesAtTime = ($definition.Triggers.Item($triggerId).StartBoundary).Substring(11, 8) $null = (Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force -Confirm:$false)
$definition.Triggers.Remove($triggerId) $ChangedSettings++
$triggerId -= 1 }
}
}
$folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null) | Out-Null
if (!$($WAUConfig.WAU_UpdatesAtTime)) { if ($null -ne $($WAUPolicies.WAU_StartMenuShortcut) -and ($($WAUPolicies.WAU_StartMenuShortcut) -ne $($WAUConfig.WAU_StartMenuShortcut)))
New-ItemProperty $regPath -Name WAU_UpdatesAtTime -Value $UpdatesAtTime -Force | Out-Null {
$Script:WAUConfig = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" $null = (New-ItemProperty -Path $regPath -Name WAU_StartMenuShortcut -Value $($WAUPolicies.WAU_StartMenuShortcut) -PropertyType DWord -Force -Confirm:$false)
}
$tasktrigger = New-ScheduledTaskTrigger -Daily -At $($WAUConfig.WAU_UpdatesAtTime) if ($WAUPolicies.WAU_StartMenuShortcut -eq 1)
{
if (!(Test-Path -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)"))
{
$null = (New-Item -ItemType Directory -Force -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Confirm:$false)
}
#Count Triggers (correctly) Add-Shortcut 'wscript.exe' "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Check for updated Apps.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`"`"" "${env:SystemRoot}\System32\shell32.dll,-16739" 'Manual start of Winget-AutoUpdate (WAU)...'
$service = New-Object -ComObject Schedule.Service Add-Shortcut 'wscript.exe' "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Open logs.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`" -Logs`"" "${env:SystemRoot}\System32\shell32.dll,-16763" 'Open existing WAU logs...'
$service.Connect($env:COMPUTERNAME) Add-Shortcut 'wscript.exe' "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Web Help.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`" -Help`"" "${env:SystemRoot}\System32\shell32.dll,-24" 'Help for WAU...'
$folder = $service.GetFolder('\')
$task = $folder.GetTask("Winget-AutoUpdate")
$definition = $task.Definition
$definition.Triggers.Count | Out-Null
if ($definition.Triggers.Count -gt 0) {
$triggers = @()
$triggers += (Get-ScheduledTask "Winget-AutoUpdate").Triggers
$triggers += $tasktrigger
Set-ScheduledTask -TaskName "Winget-AutoUpdate" -Trigger $triggers
}
else {
Set-ScheduledTask -TaskName "Winget-AutoUpdate" -Trigger $tasktrigger
}
$ChangedSettings++
} }
else
{
$null = (Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force -Confirm:$false)
}
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_StartMenuShortcut) -and ($($WAUConfig.WAU_StartMenuShortcut) -or $($WAUConfig.WAU_StartMenuShortcut) -eq 0))
{
$null = (Remove-ItemProperty -Path $regPath -Name WAU_StartMenuShortcut -Force -ErrorAction SilentlyContinue -Confirm:$false)
$null = (Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force -Confirm:$false)
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UpdatesAtLogon) -and ($($WAUPolicies.WAU_UpdatesAtLogon) -ne $($WAUConfig.WAU_UpdatesAtLogon))) { if ($null -ne $($WAUPolicies.WAU_MaxLogFiles) -and ($($WAUPolicies.WAU_MaxLogFiles) -ne $($WAUConfig.WAU_MaxLogFiles)))
if ($WAUPolicies.WAU_UpdatesAtLogon -eq 1) { {
New-ItemProperty $regPath -Name WAU_UpdatesAtLogon -Value $($WAUPolicies.WAU_UpdatesAtLogon) -PropertyType DWord -Force | Out-Null $null = (New-ItemProperty -Path $regPath -Name WAU_MaxLogFiles -Value $($WAUPolicies.WAU_MaxLogFiles.TrimEnd(' ', '\', '/')) -Force -Confirm:$false)
$triggers = @() $ChangedSettings++
$triggers += (Get-ScheduledTask "Winget-AutoUpdate").Triggers }
#Count Triggers (correctly) elseif ($null -eq $($WAUPolicies.WAU_MaxLogFiles) -and $($WAUConfig.WAU_MaxLogFiles) -ne 3)
$service = New-Object -ComObject Schedule.Service {
$service.Connect($env:COMPUTERNAME) $null = (New-ItemProperty -Path $regPath -Name WAU_MaxLogFiles -Value 3 -Force -Confirm:$false)
$folder = $service.GetFolder('\') $ChangedSettings++
$task = $folder.GetTask("Winget-AutoUpdate") }
$definition = $task.Definition
$triggerLogon = $false
foreach ($trigger in $definition.Triggers) {
if ($trigger.Type -eq "9") {
$triggerLogon = $true
break
}
}
if (!$triggerLogon) {
$triggers += New-ScheduledTaskTrigger -AtLogon
Set-ScheduledTask -TaskName "Winget-AutoUpdate" -Trigger $triggers
}
}
else {
New-ItemProperty $regPath -Name WAU_UpdatesAtLogon -Value $($WAUPolicies.WAU_UpdatesAtLogon) -PropertyType DWord -Force | Out-Null
$service = New-Object -ComObject Schedule.Service
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask("Winget-AutoUpdate")
$definition = $task.Definition
$definition.Triggers.Count | Out-Null
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++) {
if ($definition.Triggers.Item($triggerId).Type -eq "9") {
$definition.Triggers.Remove($triggerId)
$triggerId -= 1
}
}
$folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null) | Out-Null
}
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_UpdatesAtLogon) -and ($($WAUConfig.WAU_UpdatesAtLogon) -or $($WAUConfig.WAU_UpdatesAtLogon) -eq 0)) {
Remove-ItemProperty $regPath -Name WAU_UpdatesAtLogon -Force -ErrorAction SilentlyContinue | Out-Null
$service = New-Object -ComObject Schedule.Service
$service.Connect($env:COMPUTERNAME)
$folder = $service.GetFolder('\')
$task = $folder.GetTask("Winget-AutoUpdate")
$definition = $task.Definition
for ($triggerId = 1; $triggerId -le $definition.Triggers.Count; $triggerId++) {
if ($definition.Triggers.Item($triggerId).Type -eq "9") {
$definition.Triggers.Remove($triggerId)
$triggerId -= 1
}
}
$folder.RegisterTaskDefinition($task.Name, $definition, 4, $null, $null, $null) | Out-Null
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_UserContext) -and ($($WAUPolicies.WAU_UserContext) -ne $($WAUConfig.WAU_UserContext))) { if ($null -ne $($WAUPolicies.WAU_MaxLogSize) -and ($($WAUPolicies.WAU_MaxLogSize) -ne $($WAUConfig.WAU_MaxLogSize)))
New-ItemProperty $regPath -Name WAU_UserContext -Value $($WAUPolicies.WAU_UserContext) -PropertyType DWord -Force | Out-Null {
if ($WAUPolicies.WAU_UserContext -eq 1) { $null = (New-ItemProperty -Path $regPath -Name WAU_MaxLogSize -Value $($WAUPolicies.WAU_MaxLogSize.TrimEnd(' ', '\', '/')) -Force -Confirm:$false)
# Settings for the scheduled task in User context $ChangedSettings++
$taskAction = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\winget-upgrade.ps1`"`"" }
$taskUserPrincipal = New-ScheduledTaskPrincipal -GroupId S-1-5-11 elseif ($null -eq $($WAUPolicies.WAU_MaxLogSize) -and $($WAUConfig.WAU_MaxLogSize) -ne 1048576)
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 03:00:00 {
$null = (New-ItemProperty -Path $regPath -Name WAU_MaxLogSize -Value 1048576 -Force -Confirm:$false)
$ChangedSettings++
}
# Set up the task for user apps # Get WAU Configurations after Policies change
$task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings $Script:WAUConfig = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate')
Register-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -InputObject $task -Force }
} }
else {
Get-ScheduledTask -TaskName "Winget-AutoUpdate-UserContext" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$False
}
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_UserContext) -and ($($WAUConfig.WAU_UserContext) -or $($WAUConfig.WAU_UserContext) -eq 0)) {
Remove-ItemProperty $regPath -Name WAU_UserContext -Force -ErrorAction SilentlyContinue | Out-Null
Get-ScheduledTask -TaskName "Winget-AutoUpdate-UserContext" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$False
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_DesktopShortcut) -and ($($WAUPolicies.WAU_DesktopShortcut) -ne $($WAUConfig.WAU_DesktopShortcut))) { return $($WAUPolicies.WAU_ActivateGPOManagement), $ChangedSettings
New-ItemProperty $regPath -Name WAU_DesktopShortcut -Value $($WAUPolicies.WAU_DesktopShortcut) -PropertyType DWord -Force | Out-Null
if ($WAUPolicies.WAU_DesktopShortcut -eq 1) {
Add-Shortcut "wscript.exe" "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`"`"" "${env:SystemRoot}\System32\shell32.dll,-16739" "Manual start of Winget-AutoUpdate (WAU)..."
}
else {
Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force | Out-Null
}
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_DesktopShortcut) -and ($($WAUConfig.WAU_DesktopShortcut) -or $($WAUConfig.WAU_DesktopShortcut) -eq 0)) {
Remove-ItemProperty $regPath -Name WAU_DesktopShortcut -Force -ErrorAction SilentlyContinue | Out-Null
Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force | Out-Null
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_StartMenuShortcut) -and ($($WAUPolicies.WAU_StartMenuShortcut) -ne $($WAUConfig.WAU_StartMenuShortcut))) {
New-ItemProperty $regPath -Name WAU_StartMenuShortcut -Value $($WAUPolicies.WAU_StartMenuShortcut) -PropertyType DWord -Force | Out-Null
if ($WAUPolicies.WAU_StartMenuShortcut -eq 1) {
if (!(Test-Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)")) {
New-Item -ItemType Directory -Force -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" | Out-Null
}
Add-Shortcut "wscript.exe" "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Check for updated Apps.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`"`"" "${env:SystemRoot}\System32\shell32.dll,-16739" "Manual start of Winget-AutoUpdate (WAU)..."
Add-Shortcut "wscript.exe" "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Open logs.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`" -Logs`"" "${env:SystemRoot}\System32\shell32.dll,-16763" "Open existing WAU logs..."
Add-Shortcut "wscript.exe" "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Web Help.lnk" "`"$($WAUConfig.InstallLocation)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WAUConfig.InstallLocation)\user-run.ps1`" -Help`"" "${env:SystemRoot}\System32\shell32.dll,-24" "Help for WAU..."
}
else {
Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force | Out-Null
}
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_StartMenuShortcut) -and ($($WAUConfig.WAU_StartMenuShortcut) -or $($WAUConfig.WAU_StartMenuShortcut) -eq 0)) {
Remove-ItemProperty $regPath -Name WAU_StartMenuShortcut -Force -ErrorAction SilentlyContinue | Out-Null
Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force | Out-Null
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_MaxLogFiles) -and ($($WAUPolicies.WAU_MaxLogFiles) -ne $($WAUConfig.WAU_MaxLogFiles))) {
New-ItemProperty $regPath -Name WAU_MaxLogFiles -Value $($WAUPolicies.WAU_MaxLogFiles.TrimEnd(" ", "\", "/")) -Force | Out-Null
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_MaxLogFiles) -and $($WAUConfig.WAU_MaxLogFiles) -ne 3) {
New-ItemProperty $regPath -Name WAU_MaxLogFiles -Value 3 -Force | Out-Null
$ChangedSettings++
}
if ($null -ne $($WAUPolicies.WAU_MaxLogSize) -and ($($WAUPolicies.WAU_MaxLogSize) -ne $($WAUConfig.WAU_MaxLogSize))) {
New-ItemProperty $regPath -Name WAU_MaxLogSize -Value $($WAUPolicies.WAU_MaxLogSize.TrimEnd(" ", "\", "/")) -Force | Out-Null
$ChangedSettings++
}
elseif ($null -eq $($WAUPolicies.WAU_MaxLogSize) -and $($WAUConfig.WAU_MaxLogSize) -ne 1048576) {
New-ItemProperty $regPath -Name WAU_MaxLogSize -Value 1048576 -Force | Out-Null
$ChangedSettings++
}
#Get WAU Configurations after Policies change
$Script:WAUConfig = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate"
}
}
Return $($WAUPolicies.WAU_ActivateGPOManagement), $ChangedSettings
} }

View File

@ -1,25 +1,22 @@
#Function to get the latest WAU available version on Github # Function to get the latest WAU available version on Github
function Get-WAUAvailableVersion { function Get-WAUAvailableVersion
{
# Get Github latest version
if ($WAUConfig.WAU_UpdatePrerelease -eq 1)
{
# Log
Write-ToLog -LogMsg 'WAU AutoUpdate Pre-release versions is Enabled' -LogColor 'Cyan'
#Get Github latest version # Get latest pre-release info
if ($WAUConfig.WAU_UpdatePrerelease -eq 1) { $WAUurl = 'https://api.github.com/repos/Romanitho/Winget-AutoUpdate/releases'
}
#Log else
Write-ToLog "WAU AutoUpdate Pre-release versions is Enabled" "Cyan" {
# Get latest stable info
#Get latest pre-release info $WAUurl = 'https://api.github.com/repos/Romanitho/Winget-AutoUpdate/releases/latest'
$WAUurl = 'https://api.github.com/repos/Romanitho/Winget-AutoUpdate/releases' }
}
else {
#Get latest stable info
$WAUurl = 'https://api.github.com/repos/Romanitho/Winget-AutoUpdate/releases/latest'
}
#Return version
return ((Invoke-WebRequest $WAUurl -UseBasicParsing | ConvertFrom-Json)[0].tag_name).Replace("v", "")
# Return version
return ((Invoke-WebRequest -Uri $WAUurl -UseBasicParsing | ConvertFrom-Json)[0].tag_name).Replace('v', '')
} }

View File

@ -1,41 +1,53 @@
#Function to get the winget command regarding execution context (User, System...) # Function to get the winget command regarding execution context (User, System...)
Function Get-WingetCmd { function Get-WingetCmd
{
#Get WinGet Path (if Admin context) # Get WinGet Path (if Admin context)
# Includes Workaround for ARM64 (removed X64 and replaces it with a wildcard) # Includes Workaround for ARM64 (removed X64 and replaces it with a wildcard)
$ResolveWingetPath = Resolve-Path "$env:ProgramFiles\WindowsApps\Microsoft.DesktopAppInstaller_*_*__8wekyb3d8bbwe" | Sort-Object { [version]($_.Path -replace '^[^\d]+_((\d+\.)*\d+)_.*', '$1') } $ResolveWingetPath = (Resolve-Path -Path "$env:ProgramFiles\WindowsApps\Microsoft.DesktopAppInstaller_*_*__8wekyb3d8bbwe" | Sort-Object -Property {
[version]($_.Path -replace '^[^\d]+_((\d+\.)*\d+)_.*', '$1')
})
if ($ResolveWingetPath) { if ($ResolveWingetPath)
#If multiple version, pick last one {
$WingetPath = $ResolveWingetPath[-1].Path # If multiple version, pick last one
} $WingetPath = $ResolveWingetPath[-1].Path
}
#If running under System or Admin context obtain Winget from Program Files #If running under System or Admin context obtain Winget from Program Files
if((([System.Security.Principal.WindowsIdentity]::GetCurrent().User) -eq "S-1-5-18") -or ($WingetPath)){ if ((([Security.Principal.WindowsIdentity]::GetCurrent().User) -eq 'S-1-5-18') -or ($WingetPath))
if (Test-Path "$WingetPath\winget.exe") { {
$Script:Winget = "$WingetPath\winget.exe" if (Test-Path -Path ('{0}\winget.exe' -f $WingetPath) -ErrorAction SilentlyContinue)
} {
}else{ $Script:Winget = ('{0}\winget.exe' -f $WingetPath)
#Get Winget Location in User context }
$WingetCmd = Get-Command winget.exe -ErrorAction SilentlyContinue }
if ($WingetCmd) { else
$Script:Winget = $WingetCmd.Source {
} #Get Winget Location in User context
} $WingetCmd = (Get-Command -Name winget.exe -ErrorAction SilentlyContinue)
If(!($Script:Winget)){ if ($WingetCmd)
Write-ToLog "Winget not installed or detected !" "Red" {
return $false $Script:Winget = $WingetCmd.Source
} }
}
#Run winget to list apps and accept source agrements (necessary on first run) if (!($Script:Winget))
& $Winget list --accept-source-agreements -s winget | Out-Null {
Write-ToLog 'Winget not installed or detected !' 'Red'
#Log Winget installed version return $false
$WingetVer = & $Winget --version }
Write-ToLog "Winget Version: $WingetVer"
return $true # Run winget to list apps and accept source agrements (necessary on first run)
$null = (& $Winget list --accept-source-agreements -s winget)
# Log Winget installed version
$WingetVer = & $Winget --version
Write-ToLog ('Winget Version: {0}' -f $WingetVer)
return $true
} }

View File

@ -1,76 +1,92 @@
#Function to get the outdated app list, in formatted array # Function to get the outdated app list, in formatted array
function Get-WingetOutdatedApps { function Get-WingetOutdatedApps
class Software { {
[string]$Name class Software {
[string]$Id [string]$Name
[string]$Version [string]$Id
[string]$AvailableVersion [string]$Version
} [string]$AvailableVersion
}
#Get list of available upgrades on winget format # Get list of available upgrades on winget format
$upgradeResult = & $Winget upgrade --source winget | Out-String $upgradeResult = (& $Winget upgrade --source winget | Out-String)
#Start Convertion of winget format to an array. Check if "-----" exists (Winget Error Handling) # Start Convertion of winget format to an array. Check if "-----" exists (Winget Error Handling)
if (!($upgradeResult -match "-----")) { if (!($upgradeResult -match '-----'))
return "An unusual thing happened (maybe all apps are upgraded):`n$upgradeResult" {
} return "An unusual thing happened (maybe all apps are upgraded):`n$upgradeResult"
}
#Split winget output to lines # Split winget output to lines
$lines = $upgradeResult.Split([Environment]::NewLine) | Where-Object { $_ } $lines = $upgradeResult.Split([Environment]::NewLine) | Where-Object -FilterScript {
$_
}
# Find the line that starts with "------" # Find the line that starts with "------"
$fl = 0 $fl = 0
while (-not $lines[$fl].StartsWith("-----")) { while (-not $lines[$fl].StartsWith('-----'))
$fl++ {
} $fl++
}
#Get header line # Get header line
$fl = $fl - 1 $fl = $fl - 1
#Get header titles [without remove seperator] # Get header titles [without remove seperator]
$index = $lines[$fl] -split '(?<=\s)(?!\s)' $index = $lines[$fl] -split '(?<=\s)(?!\s)'
# Line $fl has the header, we can find char where we find ID and Version [and manage non latin characters] # Line $fl has the header, we can find char where we find ID and Version [and manage non latin characters]
$idStart = $($index[0] -replace '[\u4e00-\u9fa5]', '**').Length $idStart = $($index[0] -replace '[\u4e00-\u9fa5]', '**').Length
$versionStart = $idStart + $($index[1] -replace '[\u4e00-\u9fa5]', '**').Length $versionStart = $idStart + $($index[1] -replace '[\u4e00-\u9fa5]', '**').Length
$availableStart = $versionStart + $($index[2] -replace '[\u4e00-\u9fa5]', '**').Length $availableStart = $versionStart + $($index[2] -replace '[\u4e00-\u9fa5]', '**').Length
# Now cycle in real package and split accordingly # Now cycle in real package and split accordingly
$upgradeList = @() $upgradeList = @()
For ($i = $fl + 2; $i -lt $lines.Length; $i++) {
$line = $lines[$i] -replace "[\u2026]", " " #Fix "..." in long names
if ($line.StartsWith("-----")) {
#Get header line
$fl = $i - 1
#Get header titles [without remove seperator] for ($i = $fl + 2; $i -lt $lines.Length; $i++)
$index = $lines[$fl] -split '(?<=\s)(?!\s)' {
$line = $lines[$i] -replace '[\u2026]', ' ' #Fix "..." in long names
# Line $fl has the header, we can find char where we find ID and Version [and manage non latin characters] if ($line.StartsWith('-----'))
$idStart = $($index[0] -replace '[\u4e00-\u9fa5]', '**').Length {
$versionStart = $idStart + $($index[1] -replace '[\u4e00-\u9fa5]', '**').Length # Get header line
$availableStart = $versionStart + $($index[2] -replace '[\u4e00-\u9fa5]', '**').Length $fl = $i - 1
}
#(Alphanumeric | Literal . | Alphanumeric) - the only unique thing in common for lines with applications
if ($line -match "\w\.\w") {
$software = [Software]::new()
#Manage non latin characters
$nameDeclination = $($line.Substring(0, $idStart) -replace '[\u4e00-\u9fa5]', '**').Length - $line.Substring(0, $idStart).Length
$software.Name = $line.Substring(0, $idStart - $nameDeclination).TrimEnd()
$software.Id = $line.Substring($idStart - $nameDeclination, $versionStart - $idStart).TrimEnd()
$software.Version = $line.Substring($versionStart - $nameDeclination, $availableStart - $versionStart).TrimEnd()
$software.AvailableVersion = $line.Substring($availableStart - $nameDeclination).TrimEnd()
#add formated soft to list
$upgradeList += $software
}
}
#If current user is not system, remove system apps from list # Get header titles [without remove seperator]
if ($IsSystem -eq $false) { $index = $lines[$fl] -split '(?<=\s)(?!\s)'
$SystemApps = Get-Content -Path "$WorkingDir\winget_system_apps.txt"
$upgradeList = $upgradeList | Where-Object { $SystemApps -notcontains $_.Id }
}
return $upgradeList | Sort-Object { Get-Random } # Line $fl has the header, we can find char where we find ID and Version [and manage non latin characters]
$idStart = $($index[0] -replace '[\u4e00-\u9fa5]', '**').Length
$versionStart = $idStart + $($index[1] -replace '[\u4e00-\u9fa5]', '**').Length
$availableStart = $versionStart + $($index[2] -replace '[\u4e00-\u9fa5]', '**').Length
}
# (Alphanumeric | Literal . | Alphanumeric) - the only unique thing in common for lines with applications
if ($line -match '\w\.\w')
{
$software = [Software]::new()
# Manage non latin characters
$nameDeclination = $($line.Substring(0, $idStart) -replace '[\u4e00-\u9fa5]', '**').Length - $line.Substring(0, $idStart).Length
$software.Name = $line.Substring(0, $idStart - $nameDeclination).TrimEnd()
$software.Id = $line.Substring($idStart - $nameDeclination, $versionStart - $idStart).TrimEnd()
$software.Version = $line.Substring($versionStart - $nameDeclination, $availableStart - $versionStart).TrimEnd()
$software.AvailableVersion = $line.Substring($availableStart - $nameDeclination).TrimEnd()
# add formated soft to list
$upgradeList += $software
}
}
# If current user is not system, remove system apps from list
if ($IsSystem -eq $false)
{
$SystemApps = Get-Content -Path ('{0}\winget_system_apps.txt' -f $WorkingDir)
$upgradeList = $upgradeList | Where-Object -FilterScript {
$SystemApps -notcontains $_.Id
}
}
return $upgradeList | Sort-Object -Property {
Get-Random
}
} }

View File

@ -1,18 +1,17 @@
function Get-WingetSystemApps { function Get-WingetSystemApps
{
# Json File, where to export system installed apps
$jsonFile = ('{0}\winget_system_apps.txt' -f $WorkingDir)
#Json File, where to export system installed apps # Get list of installed Winget apps to json file
$jsonFile = "$WorkingDir\winget_system_apps.txt" $null = (& $Winget export -o $jsonFile --accept-source-agreements -s winget)
#Get list of installed Winget apps to json file # Convert json file to txt file with app ids
& $Winget export -o $jsonFile --accept-source-agreements -s winget | Out-Null $InstalledApps = (Get-Content -Path $jsonFile | ConvertFrom-Json)
#Convert json file to txt file with app ids # Save app list
$InstalledApps = get-content $jsonFile | ConvertFrom-Json $null = (Set-Content -Value $InstalledApps.Sources.Packages.PackageIdentifier -Path $jsonFile -Force -Confirm:$False -ErrorAction SilentlyContinue)
#Save app list
Set-Content $InstalledApps.Sources.Packages.PackageIdentifier -Path $jsonFile
#Sort app list
Get-Content $jsonFile | Sort-Object | Set-Content $jsonFile
# Sort app list
$null = (Get-Content -Path $jsonFile | Sort-Object | Set-Content -Path $jsonFile -Force -Confirm:$False -ErrorAction SilentlyContinue)
} }

View File

@ -1,95 +1,118 @@
#Function to rotate the logs # Function to rotate the logs
function Invoke-LogRotation ($LogFile, $MaxLogFiles, $MaxLogSize) { function Invoke-LogRotation
<# {
.SYNOPSIS <#
Handle log rotation. .SYNOPSIS
.DESCRIPTION Handle log rotation.
Invoke-LogRotation handles log rotation .DESCRIPTION
.NOTES Invoke-LogRotation handles log rotation
Author: Øyvind Kallstad (Minimized and changed for WAU 12.01.2023 by Göran Axel Johannesson) .NOTES
URL: https://www.powershellgallery.com/packages/Communary.Logger/1.1 Author: Øyvind Kallstad (Minimized and changed for WAU 12.01.2023 by Göran Axel Johannesson)
Date: 21.11.2014 URL: https://www.powershellgallery.com/packages/Communary.Logger/1.1
Version: 1.0 Date: 21.11.2014
#> Version: 1.0
#>
param
(
[string]
$LogFile,
[int]
$MaxLogFiles,
[int]
$MaxLogSize
)
try { try
# get current size of log file {
$currentSize = (Get-Item $LogFile).Length # get current size of log file
$currentSize = (Get-Item -Path $LogFile).Length
# get log name # get log name
$logFileName = Split-Path $LogFile -Leaf $logFileName = (Split-Path -Path $LogFile -Leaf)
$logFilePath = Split-Path $LogFile $logFilePath = (Split-Path -Path $LogFile)
$logFileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($logFileName) $logFileNameWithoutExtension = [IO.Path]::GetFileNameWithoutExtension($logFileName)
$logFileNameExtension = [System.IO.Path]::GetExtension($logFileName) $logFileNameExtension = [IO.Path]::GetExtension($logFileName)
# if MaxLogFiles is 1 just keep the original one and let it grow # if MaxLogFiles is 1 just keep the original one and let it grow
if (-not($MaxLogFiles -eq 1)) { if (-not ($MaxLogFiles -eq 1))
if ($currentSize -ge $MaxLogSize) { {
if ($currentSize -ge $MaxLogSize)
{
# construct name of archived log file
$newLogFileName = $logFileNameWithoutExtension + (Get-Date -Format 'yyyyMMddHHmmss').ToString() + $logFileNameExtension
# construct name of archived log file # copy old log file to new using the archived name constructed above
$newLogFileName = $logFileNameWithoutExtension + (Get-Date -Format 'yyyyMMddHHmmss').ToString() + $logFileNameExtension $null = (Copy-Item -Path $LogFile -Destination (Join-Path -Path (Split-Path -Path $LogFile) -ChildPath $newLogFileName))
# copy old log file to new using the archived name constructed above # Create a new log file
Copy-Item -Path $LogFile -Destination (Join-Path (Split-Path $LogFile) $newLogFileName) try
{
# Create a new log file $null = (Remove-Item -Path $LogFile -Force -Confirm:$False -ErrorAction SilentlyContinue)
try { $null = (New-Item -ItemType File -Path $LogFile -Force -Confirm:$False -ErrorAction SilentlyContinue)
Remove-Item -Path $LogFile -Force # Set ACL for users on logfile
New-Item -ItemType File -Path $LogFile -Force $NewAcl = (Get-Acl -Path $LogFile)
#Set ACL for users on logfile $identity = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList S-1-5-11)
$NewAcl = Get-Acl -Path $LogFile $fileSystemRights = 'Modify'
$identity = New-Object System.Security.Principal.SecurityIdentifier S-1-5-11 $type = 'Allow'
$fileSystemRights = "Modify" $fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type
$type = "Allow" $fileSystemAccessRule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList)
$fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type $NewAcl.SetAccessRule($fileSystemAccessRule)
$fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList $null = (Set-Acl -Path $LogFile -AclObject $NewAcl)
$NewAcl.SetAccessRule($fileSystemAccessRule)
Set-Acl -Path $LogFile -AclObject $NewAcl
}
catch {
Return $False
}
# if MaxLogFiles is 0 don't delete any old archived log files
if (-not($MaxLogFiles -eq 0)) {
# set filter to search for archived log files
$archivedLogFileFilter = $logFileNameWithoutExtension + '??????????????' + $logFileNameExtension
# get archived log files
$oldLogFiles = Get-Item -Path "$(Join-Path -Path $logFilePath -ChildPath $archivedLogFileFilter)"
if ([bool]$oldLogFiles) {
# compare found log files to MaxLogFiles parameter of the log object, and delete oldest until we are
# back to the correct number
if (($oldLogFiles.Count + 1) -gt $MaxLogFiles) {
[int]$numTooMany = (($oldLogFiles.Count) + 1) - $MaxLogFiles
$oldLogFiles | Sort-Object 'LastWriteTime' | Select-Object -First $numTooMany | Remove-Item
}
}
}
#Log Header
$Log = "##################################################`n# CHECK FOR APP UPDATES - $(Get-Date -Format (Get-culture).DateTimeFormat.ShortDatePattern)`n##################################################"
$Log | out-file -filepath $LogFile -Append
Write-ToLog "Running in System context"
if ($ActivateGPOManagement) {
Write-ToLog "Activated WAU GPO Management detected, comparing..."
if ($null -ne $ChangedSettings -and $ChangedSettings -ne 0) {
Write-ToLog "Changed settings detected and applied" "Yellow"
}
else {
Write-ToLog "No Changed settings detected" "Yellow"
}
}
Write-ToLog "Max Log Size reached: $MaxLogSize bytes - Rotated Logs"
Return $True
} }
} catch
} {
catch { return $False
Return $False }
}
# if MaxLogFiles is 0 don't delete any old archived log files
if (-not ($MaxLogFiles -eq 0))
{
# set filter to search for archived log files
$archivedLogFileFilter = $logFileNameWithoutExtension + '??????????????' + $logFileNameExtension
# get archived log files
$oldLogFiles = (Get-Item -Path "$(Join-Path -Path $logFilePath -ChildPath $archivedLogFileFilter)")
if ([bool]$oldLogFiles)
{
# compare found log files to MaxLogFiles parameter of the log object, and delete oldest until we are
# back to the correct number
if (($oldLogFiles.Count + 1) -gt $MaxLogFiles)
{
[int]$numTooMany = (($oldLogFiles.Count) + 1) - $MaxLogFiles
$null = ($oldLogFiles | Sort-Object -Property 'LastWriteTime' | Select-Object -First $numTooMany | Remove-Item -Force -Confirm:$False -ErrorAction SilentlyContinue)
}
}
}
# Log Header
$Log = "##################################################`n# CHECK FOR APP UPDATES - $(Get-Date -Format (Get-Culture).DateTimeFormat.ShortDatePattern)`n##################################################"
$null = ($Log | Out-File -FilePath $LogFile -Append -Force)
Write-ToLog -LogMsg 'Running in System context'
if ($ActivateGPOManagement)
{
Write-ToLog -LogMsg 'Activated WAU GPO Management detected, comparing...'
if ($null -ne $ChangedSettings -and $ChangedSettings -ne 0)
{
Write-ToLog -LogMsg 'Changed settings detected and applied' -LogColor 'Yellow'
}
else
{
Write-ToLog -LogMsg 'No Changed settings detected' -LogColor 'Yellow'
}
}
Write-ToLog -LogMsg ('Max Log Size reached: {0} bytes - Rotated Logs' -f $MaxLogSize)
return $True
}
}
}
catch
{
return $False
}
} }

View File

@ -1,65 +1,82 @@
#Function to check if the mods directory is secured. # Function to check if the mods directory is secured.
#Security: Mods directory must be protected (Users could create scripts of their own - then they'll run in System Context)! # Security: Mods directory must be protected (Users could create scripts of their own - then they'll run in System Context)!
#Check if Local Users have write rights in Mods directory or not (and take action if necessary): # Check if Local Users have write rights in Mods directory or not (and take action if necessary):
function Invoke-ModsProtect ($ModsPath) { function Invoke-ModsProtect
try { {
$directory = Get-Item -Path $ModsPath -ErrorAction SilentlyContinue [CmdletBinding()]
$acl = Get-Acl -Path $directory.FullName param
#Local Users - S-1-5-32-545 (
$userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-545") [string]
#Translate SID to Locale Name $ModsPath
$ntAccount = $userSID.Translate([System.Security.Principal.NTAccount]) )
$userName = $ntAccount.Value
$userRights = [System.Security.AccessControl.FileSystemRights]"Write"
$hasWriteAccess = $False try
{
$directory = (Get-Item -Path $ModsPath -ErrorAction SilentlyContinue)
$acl = (Get-Acl -Path $directory.FullName)
# Local Users - S-1-5-32-545
$userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-32-545'))
# Translate SID to Locale Name
$ntAccount = $userSID.Translate([Security.Principal.NTAccount])
$userName = $ntAccount.Value
$userRights = [Security.AccessControl.FileSystemRights]'Write'
$hasWriteAccess = $False
foreach ($access in $acl.Access) { foreach ($access in $acl.Access)
if ($access.IdentityReference.Value -eq $userName -and $access.FileSystemRights -eq $userRights) { {
$hasWriteAccess = $True if ($access.IdentityReference.Value -eq $userName -and $access.FileSystemRights -eq $userRights)
break {
} $hasWriteAccess = $True
} break
}
}
if ($hasWriteAccess) { if ($hasWriteAccess)
#Disable inheritance {
$acl.SetAccessRuleProtection($True, $True) # Disable inheritance
# Remove any existing rules $acl.SetAccessRuleProtection($True, $True)
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) }
#SYSTEM Full - S-1-5-18
$userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-18")
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule)
# Save the updated ACL
Set-Acl -Path $directory.FullName -AclObject $acl
#Administrators Full - S-1-5-32-544 # Remove any existing rules
$acl = Get-Acl -Path $directory.FullName $acl.Access | ForEach-Object -Process {
$userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-544") $acl.RemoveAccessRule($_)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") }
$acl.SetAccessRule($rule)
Set-Acl -Path $directory.FullName -AclObject $acl
#Local Users ReadAndExecute - S-1-5-32-545 S-1-5-11 # SYSTEM Full - S-1-5-18
$acl = Get-Acl -Path $directory.FullName $userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-18'))
$userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-545") $rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow") $acl.SetAccessRule($rule)
$acl.SetAccessRule($rule) # Save the updated ACL
Set-Acl -Path $directory.FullName -AclObject $acl $null = (Set-Acl -Path $directory.FullName -AclObject $acl)
#Authenticated Users ReadAndExecute - S-1-5-11 # Administrators Full - S-1-5-32-544
$acl = Get-Acl -Path $directory.FullName $acl = (Get-Acl -Path $directory.FullName)
$userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-11") $userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-32-544'))
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow") $rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
$acl.SetAccessRule($rule) $acl.SetAccessRule($rule)
Set-Acl -Path $directory.FullName -AclObject $acl $null = (Set-Acl -Path $directory.FullName -AclObject $acl)
return $True # Local Users ReadAndExecute - S-1-5-32-545 S-1-5-11
} $acl = (Get-Acl -Path $directory.FullName)
return $False $userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-32-545'))
} $rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
catch { $acl.SetAccessRule($rule)
return "Error" $null = (Set-Acl -Path $directory.FullName -AclObject $acl)
}
# Authenticated Users ReadAndExecute - S-1-5-11
$acl = (Get-Acl -Path $directory.FullName)
$userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-11'))
$rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
$acl.SetAccessRule($rule)
$null = (Set-Acl -Path $directory.FullName -AclObject $acl)
return $True
}
return $False
}
catch
{
return 'Error'
}
} }

View File

@ -1,231 +1,289 @@
#Function to make actions after WAU update # Function to make actions after WAU update
function Invoke-PostUpdateActions { function Invoke-PostUpdateActions
{
# log
Write-ToLog -LogMsg 'Running Post Update actions:' -LogColor 'yellow'
#log # Check if Intune Management Extension Logs folder and WAU-updates.log exists, make symlink
Write-ToLog "Running Post Update actions:" "yellow" if ((Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs" -ErrorAction SilentlyContinue) -and !(Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -ErrorAction SilentlyContinue))
{
Write-ToLog -LogMsg '-> Creating SymLink for log file in Intune Management Extension log folder' -LogColor 'yellow'
$null = New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -ItemType SymbolicLink -Value $LogFile -Force -ErrorAction SilentlyContinue
}
#Check if Intune Management Extension Logs folder and WAU-updates.log exists, make symlink # Check if Intune Management Extension Logs folder and WAU-install.log exists, make symlink
if ((Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs") -and !(Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log")) { if ((Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs" -ErrorAction SilentlyContinue) -and (Test-Path -Path ('{0}\logs\install.log' -f $WorkingDir) -ErrorAction SilentlyContinue) -and !(Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -ErrorAction SilentlyContinue))
Write-ToLog "-> Creating SymLink for log file in Intune Management Extension log folder" "yellow" {
New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -ItemType SymbolicLink -Value $LogFile -Force -ErrorAction SilentlyContinue | Out-Null Write-Host -Object "`nCreating SymLink for log file (WAU-install) in Intune Management Extension log folder" -ForegroundColor Yellow
} $null = (New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -ItemType SymbolicLink -Value ('{0}\logs\install.log' -f $WorkingDir) -Force -Confirm:$False -ErrorAction SilentlyContinue)
#Check if Intune Management Extension Logs folder and WAU-install.log exists, make symlink }
if ((Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs") -and (Test-Path "$WorkingDir\logs\install.log") -and !(Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log")) {
Write-host "`nCreating SymLink for log file (WAU-install) in Intune Management Extension log folder" -ForegroundColor Yellow
New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -ItemType SymbolicLink -Value "$WorkingDir\logs\install.log" -Force -ErrorAction SilentlyContinue | Out-Null
}
Write-ToLog "-> Checking prerequisites..." "yellow" Write-ToLog -LogMsg '-> Checking prerequisites...' -LogColor 'yellow'
#Check if Visual C++ 2019 or 2022 installed # Check if Visual C++ 2019 or 2022 installed
$Visual2019 = "Microsoft Visual C++ 2015-2019 Redistributable*" $Visual2019 = 'Microsoft Visual C++ 2015-2019 Redistributable*'
$Visual2022 = "Microsoft Visual C++ 2015-2022 Redistributable*" $Visual2022 = 'Microsoft Visual C++ 2015-2022 Redistributable*'
$path = Get-Item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object { $_.GetValue("DisplayName") -like $Visual2019 -or $_.GetValue("DisplayName") -like $Visual2022 } $path = (Get-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' -ErrorAction SilentlyContinue | Where-Object -FilterScript {
$_.GetValue('DisplayName') -like $Visual2019 -or $_.GetValue('DisplayName') -like $Visual2022
})
#If not installed, install # If not installed, install
if (!($path)) { if (!($path))
try { {
if ((Get-CimInStance Win32_OperatingSystem).OSArchitecture -like "*64*") { try
$OSArch = "x64" {
} if ((Get-CimInstance -ClassName Win32_OperatingSystem).OSArchitecture -like '*64*')
else { {
$OSArch = "x86" $OSArch = 'x64'
} }
Write-ToLog "-> Downloading VC_redist.$OSArch.exe..." else
$SourceURL = "https://aka.ms/vs/17/release/VC_redist.$OSArch.exe" {
$Installer = "$($WAUConfig.InstallLocation)\VC_redist.$OSArch.exe" $OSArch = 'x86'
$ProgressPreference = 'SilentlyContinue' }
Invoke-WebRequest $SourceURL -UseBasicParsing -OutFile (New-Item -Path $Installer -Force)
Write-ToLog "-> Installing VC_redist.$OSArch.exe..."
Start-Process -FilePath $Installer -Args "/quiet /norestart" -Wait
Remove-Item $Installer -ErrorAction Ignore
Write-ToLog "-> MS Visual C++ 2015-2022 installed successfully" "green"
}
catch {
Write-ToLog "-> MS Visual C++ 2015-2022 installation failed." "red"
}
}
else {
Write-ToLog "-> Prerequisites checked. OK" "green"
}
#Check Package Install Write-ToLog -LogMsg ('-> Downloading VC_redist.{0}.exe...' -f $OSArch)
Write-ToLog "-> Checking if Winget is installed/up to date" "yellow" $SourceURL = ('https://aka.ms/vs/17/release/VC_redist.{0}.exe' -f $OSArch)
$TestWinGet = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq "Microsoft.DesktopAppInstaller" } $Installer = ('{0}\VC_redist.{1}.exe' -f $WAUConfig.InstallLocation, $OSArch)
$ProgressPreference = 'SilentlyContinue'
$null = (Invoke-WebRequest -Uri $SourceURL -UseBasicParsing -OutFile (New-Item -Path $Installer -Force))
Write-ToLog -LogMsg ('-> Installing VC_redist.{0}.exe...' -f $OSArch)
Start-Process -FilePath $Installer -ArgumentList '/quiet /norestart' -Wait
Remove-Item -Path $Installer -ErrorAction Ignore
Write-ToLog -LogMsg '-> MS Visual C++ 2015-2022 installed successfully' -LogColor 'green'
}
catch
{
Write-ToLog -LogMsg '-> MS Visual C++ 2015-2022 installation failed.' -LogColor 'red'
}
}
else
{
Write-ToLog -LogMsg '-> Prerequisites checked. OK' -LogColor 'green'
}
#Current: v1.5.2201 = 1.20.2201.0 = 2023.808.2243.0 # Check Package Install
If ([Version]$TestWinGet.Version -ge "2023.808.2243.0") { Write-ToLog -LogMsg '-> Checking if Winget is installed/up to date' -LogColor 'yellow'
$TestWinGet = Get-AppxProvisionedPackage -Online | Where-Object -FilterScript {
$_.DisplayName -eq 'Microsoft.DesktopAppInstaller'
}
Write-ToLog "-> WinGet is Installed/up to date" "green" # Current: v1.5.2201 = 1.20.2201.0 = 2023.808.2243.0
if ([Version]$TestWinGet.Version -ge '2023.808.2243.0')
{
Write-ToLog -LogMsg '-> WinGet is Installed/up to date' -LogColor 'green'
}
else
{
# Download WinGet MSIXBundle
Write-ToLog -LogMsg '-> Not installed/up to date. Downloading WinGet...'
$WinGetURL = 'https://github.com/microsoft/winget-cli/releases/download/v1.5.2201/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle'
$WebClient = New-Object -TypeName System.Net.WebClient
$WebClient.DownloadFile($WinGetURL, ('{0}\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle' -f $WAUConfig.InstallLocation))
} # Install WinGet MSIXBundle
Else { try
{
Write-ToLog -LogMsg '-> Installing Winget MSIXBundle for App Installer...'
$null = Add-AppxProvisionedPackage -Online -PackagePath ('{0}\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle' -f $WAUConfig.InstallLocation) -SkipLicense
Write-ToLog -LogMsg '-> Installed Winget MSIXBundle for App Installer' -LogColor 'green'
}
catch
{
Write-ToLog -LogMsg '-> Failed to intall Winget MSIXBundle for App Installer...' -LogColor 'red'
}
#Download WinGet MSIXBundle # Remove WinGet MSIXBundle
Write-ToLog "-> Not installed/up to date. Downloading WinGet..." Remove-Item -Path ('{0}\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle' -f $WAUConfig.InstallLocation) -Force -Confirm:$False -ErrorAction Continue
$WinGetURL = "https://github.com/microsoft/winget-cli/releases/download/v1.5.2201/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" }
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($WinGetURL, "$($WAUConfig.InstallLocation)\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle")
#Install WinGet MSIXBundle # Reset Winget Sources
try { $ResolveWingetPath = Resolve-Path -Path "$env:programfiles\WindowsApps\Microsoft.DesktopAppInstaller_*_*__8wekyb3d8bbwe\winget.exe" | Sort-Object -Property {
Write-ToLog "-> Installing Winget MSIXBundle for App Installer..." [version]($_.Path -replace '^[^\d]+_((\d+\.)*\d+)_.*', '$1')
Add-AppxProvisionedPackage -Online -PackagePath "$($WAUConfig.InstallLocation)\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -SkipLicense | Out-Null }
Write-ToLog "-> Installed Winget MSIXBundle for App Installer" "green"
}
catch {
Write-ToLog "-> Failed to intall Winget MSIXBundle for App Installer..." "red"
}
#Remove WinGet MSIXBundle if ($ResolveWingetPath)
Remove-Item -Path "$($WAUConfig.InstallLocation)\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -Force -ErrorAction Continue {
# If multiple version, pick last one
$WingetPath = $ResolveWingetPath[-1].Path
& $WingetPath source reset --force
} # log
Write-ToLog -LogMsg '-> Winget sources reseted.' -LogColor 'green'
}
#Reset Winget Sources # Create WAU Regkey if not present
$ResolveWingetPath = Resolve-Path "$env:programfiles\WindowsApps\Microsoft.DesktopAppInstaller_*_*__8wekyb3d8bbwe\winget.exe" | Sort-Object { [version]($_.Path -replace '^[^\d]+_((\d+\.)*\d+)_.*', '$1') } $regPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate'
if ($ResolveWingetPath) {
#If multiple version, pick last one
$WingetPath = $ResolveWingetPath[-1].Path
& $WingetPath source reset --force
#log if (!(Test-Path -Path $regPath -ErrorAction SilentlyContinue))
Write-ToLog "-> Winget sources reseted." "green" {
} $null = (New-Item -Path $regPath -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name DisplayName -Value 'Winget-AutoUpdate (WAU)' -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name DisplayIcon -Value 'C:\Windows\System32\shell32.dll,-16739' -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name NoModify -Value 1 -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name NoRepair -Value 1 -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name Publisher -Value 'Romanitho' -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name URLInfoAbout -Value 'https://github.com/Romanitho/Winget-AutoUpdate' -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name InstallLocation -Value $WorkingDir -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name UninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WorkingDir\WAU-Uninstall.ps1`"" -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name QuietUninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WorkingDir\WAU-Uninstall.ps1`"" -Force -Confirm:$False -ErrorAction SilentlyContinue)
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatePrerelease -Value 0 -PropertyType DWord -Force -Confirm:$False -ErrorAction SilentlyContinue)
#Create WAU Regkey if not present #log
$regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" Write-ToLog -LogMsg ('-> {0} created.' -f $regPath) -LogColor 'green'
if (!(test-path $regPath)) { }
New-Item $regPath -Force
New-ItemProperty $regPath -Name DisplayName -Value "Winget-AutoUpdate (WAU)" -Force
New-ItemProperty $regPath -Name DisplayIcon -Value "C:\Windows\System32\shell32.dll,-16739" -Force
New-ItemProperty $regPath -Name NoModify -Value 1 -Force
New-ItemProperty $regPath -Name NoRepair -Value 1 -Force
New-ItemProperty $regPath -Name Publisher -Value "Romanitho" -Force
New-ItemProperty $regPath -Name URLInfoAbout -Value "https://github.com/Romanitho/Winget-AutoUpdate" -Force
New-ItemProperty $regPath -Name InstallLocation -Value $WorkingDir -Force
New-ItemProperty $regPath -Name UninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WorkingDir\WAU-Uninstall.ps1`"" -Force
New-ItemProperty $regPath -Name QuietUninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WorkingDir\WAU-Uninstall.ps1`"" -Force
New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value 0 -PropertyType DWord -Force
#log # Fix Notif where WAU_NotificationLevel is not set
Write-ToLog "-> $regPath created." "green" $regNotif = Get-ItemProperty -Path $regPath -Name WAU_NotificationLevel -ErrorAction SilentlyContinue
}
#Fix Notif where WAU_NotificationLevel is not set
$regNotif = Get-ItemProperty $regPath -Name WAU_NotificationLevel -ErrorAction SilentlyContinue
if (!$regNotif) {
New-ItemProperty $regPath -Name WAU_NotificationLevel -Value Full -Force
#log if (!$regNotif)
Write-ToLog "-> Notification level setting was missing. Fixed with 'Full' option." {
} New-ItemProperty -Path $regPath -Name WAU_NotificationLevel -Value Full -Force
#Set WAU_MaxLogFiles/WAU_MaxLogSize if not set # log
$MaxLogFiles = Get-ItemProperty $regPath -Name WAU_MaxLogFiles -ErrorAction SilentlyContinue Write-ToLog -LogMsg "-> Notification level setting was missing. Fixed with 'Full' option."
if (!$MaxLogFiles) { }
New-ItemProperty $regPath -Name WAU_MaxLogFiles -Value 3 -PropertyType DWord -Force | Out-Null
New-ItemProperty $regPath -Name WAU_MaxLogSize -Value 1048576 -PropertyType DWord -Force | Out-Null
#log # Set WAU_MaxLogFiles/WAU_MaxLogSize if not set
Write-ToLog "-> MaxLogFiles/MaxLogSize setting was missing. Fixed with 3/1048576 (in bytes, default is 1048576 = 1 MB)." $MaxLogFiles = Get-ItemProperty -Path $regPath -Name WAU_MaxLogFiles -ErrorAction SilentlyContinue
}
#Set WAU_ListPath if not set if (!$MaxLogFiles)
$ListPath = Get-ItemProperty $regPath -Name WAU_ListPath -ErrorAction SilentlyContinue {
if (!$ListPath) { $null = (New-ItemProperty -Path $regPath -Name WAU_MaxLogFiles -Value 3 -PropertyType DWord -Force -Confirm:$False -ErrorAction SilentlyContinue)
New-ItemProperty $regPath -Name WAU_ListPath -Force | Out-Null $null = (New-ItemProperty -Path $regPath -Name WAU_MaxLogSize -Value 1048576 -PropertyType DWord -Force -Confirm:$False -ErrorAction SilentlyContinue)
#log # log
Write-ToLog "-> ListPath setting was missing. Fixed with empty string." Write-ToLog -LogMsg '-> MaxLogFiles/MaxLogSize setting was missing. Fixed with 3/1048576 (in bytes, default is 1048576 = 1 MB).'
} }
#Set WAU_ModsPath if not set # Set WAU_ListPath if not set
$ModsPath = Get-ItemProperty $regPath -Name WAU_ModsPath -ErrorAction SilentlyContinue $ListPath = Get-ItemProperty -Path $regPath -Name WAU_ListPath -ErrorAction SilentlyContinue
if (!$ModsPath) {
New-ItemProperty $regPath -Name WAU_ModsPath -Force | Out-Null
#log if (!$ListPath)
Write-ToLog "-> ModsPath setting was missing. Fixed with empty string." {
} $null = (New-ItemProperty -Path $regPath -Name WAU_ListPath -Force -Confirm:$False -ErrorAction SilentlyContinue)
#Security check # log
Write-ToLog "-> Checking Mods Directory:" "yellow" Write-ToLog -LogMsg '-> ListPath setting was missing. Fixed with empty string.'
$Protected = Invoke-ModsProtect "$($WAUConfig.InstallLocation)\mods" }
if ($Protected -eq $True) {
Write-ToLog "-> The mods directory is now secured!" "green"
}
elseif ($Protected -eq $False) {
Write-ToLog "-> The mods directory was already secured!" "green"
}
else {
Write-ToLog "-> Error: The mods directory couldn't be verified as secured!" "red"
}
#Convert about.xml if exists (old WAU versions) to reg # Set WAU_ModsPath if not set
$WAUAboutPath = "$WorkingDir\config\about.xml" $ModsPath = (Get-ItemProperty -Path $regPath -Name WAU_ModsPath -ErrorAction SilentlyContinue)
if (test-path $WAUAboutPath) {
[xml]$About = Get-Content $WAUAboutPath -Encoding UTF8 -ErrorAction SilentlyContinue
New-ItemProperty $regPath -Name DisplayVersion -Value $About.app.version -Force
#Remove file once converted if (!$ModsPath)
Remove-Item $WAUAboutPath -Force -Confirm:$false {
$null = (New-ItemProperty -Path $regPath -Name WAU_ModsPath -Force -Confirm:$False -ErrorAction SilentlyContinue)
#log # log
Write-ToLog "-> $WAUAboutPath converted." "green" Write-ToLog -LogMsg '-> ModsPath setting was missing. Fixed with empty string.'
} }
#Convert config.xml if exists (previous WAU versions) to reg # Security check
$WAUConfigPath = "$WorkingDir\config\config.xml" Write-ToLog -LogMsg '-> Checking Mods Directory:' -LogColor 'yellow'
if (test-path $WAUConfigPath) { $Protected = Invoke-ModsProtect ('{0}\mods' -f $WAUConfig.InstallLocation)
[xml]$Config = Get-Content $WAUConfigPath -Encoding UTF8 -ErrorAction SilentlyContinue
if ($Config.app.WAUautoupdate -eq "False") { New-ItemProperty $regPath -Name WAU_DisableAutoUpdate -Value 1 -Force }
if ($Config.app.NotificationLevel) { New-ItemProperty $regPath -Name WAU_NotificationLevel -Value $Config.app.NotificationLevel -Force }
if ($Config.app.UseWAUWhiteList -eq "True") { New-ItemProperty $regPath -Name WAU_UseWhiteList -Value 1 -PropertyType DWord -Force }
if ($Config.app.WAUprerelease -eq "True") { New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value 1 -PropertyType DWord -Force }
#Remove file once converted if ($Protected -eq $True)
Remove-Item $WAUConfigPath -Force -Confirm:$false {
Write-ToLog -LogMsg '-> The mods directory is now secured!' -LogColor 'green'
}
elseif ($Protected -eq $False)
{
Write-ToLog -LogMsg '-> The mods directory was already secured!' -LogColor 'green'
}
else
{
Write-ToLog -LogMsg "-> Error: The mods directory couldn't be verified as secured!" -LogColor 'red'
}
#log # Convert about.xml if exists (old WAU versions) to reg
Write-ToLog "-> $WAUConfigPath converted." "green" $WAUAboutPath = ('{0}\config\about.xml' -f $WorkingDir)
}
#Remove old functions / files if (Test-Path -Path $WAUAboutPath -ErrorAction SilentlyContinue)
$FileNames = @( {
"$WorkingDir\functions\Get-WAUConfig.ps1", [xml]$About = Get-Content -Path $WAUAboutPath -Encoding UTF8 -ErrorAction SilentlyContinue
"$WorkingDir\functions\Get-WAUCurrentVersion.ps1", $null = (New-ItemProperty -Path $regPath -Name DisplayVersion -Value $About.app.version -Force -Confirm:$False -ErrorAction SilentlyContinue)
"$WorkingDir\functions\Get-WAUUpdateStatus.ps1",
"$WorkingDir\functions\Write-Log.ps1",
"$WorkingDir\Version.txt"
)
foreach ($FileName in $FileNames) {
if (Test-Path $FileName) {
Remove-Item $FileName -Force -Confirm:$false
#log # Remove file once converted
Write-ToLog "-> $FileName removed." "green" $null = (Remove-Item -Path $WAUAboutPath -Force -Confirm:$False)
}
}
#Remove old registry key #log
$RegistryKeys = @( Write-ToLog -LogMsg ('-> {0} converted.' -f $WAUAboutPath) -LogColor 'green'
"VersionMajor", }
"VersionMinor"
)
foreach ($RegistryKey in $RegistryKeys) {
if (Get-ItemProperty -Path $regPath -Name $RegistryKey -ErrorAction SilentlyContinue) {
Remove-ItemProperty -Path $regPath -Name $RegistryKey
}
}
#Reset WAU_UpdatePostActions Value # Convert config.xml if exists (previous WAU versions) to reg
$WAUConfig | New-ItemProperty -Name WAU_PostUpdateActions -Value 0 -Force $WAUConfigPath = ('{0}\config\config.xml' -f $WorkingDir)
#Get updated WAU Config if (Test-Path -Path $WAUConfigPath -ErrorAction SilentlyContinue)
$Script:WAUConfig = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" {
[xml]$Config = (Get-Content -Path $WAUConfigPath -Encoding UTF8 -ErrorAction SilentlyContinue)
#log if ($Config.app.WAUautoupdate -eq 'False')
Write-ToLog "Post Update actions finished" "green" {
$null = (New-ItemProperty -Path $regPath -Name WAU_DisableAutoUpdate -Value 1 -Force -Confirm:$False -ErrorAction SilentlyContinue)
}
if ($Config.app.NotificationLevel)
{
$null = (New-ItemProperty -Path $regPath -Name WAU_NotificationLevel -Value $Config.app.NotificationLevel -Force -Confirm:$False -ErrorAction SilentlyContinue)
}
if ($Config.app.UseWAUWhiteList -eq 'True')
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UseWhiteList -Value 1 -PropertyType DWord -Force -Confirm:$False -ErrorAction SilentlyContinue)
}
if ($Config.app.WAUprerelease -eq 'True')
{
$null = (New-ItemProperty -Path $regPath -Name WAU_UpdatePrerelease -Value 1 -PropertyType DWord -Force -Confirm:$False -ErrorAction SilentlyContinue)
}
# Remove file once converted
$null = (Remove-Item -Path $WAUConfigPath -Force -Confirm:$False)
# log
Write-ToLog -LogMsg ('-> {0} converted.' -f $WAUConfigPath) -LogColor 'green'
}
# Remove old functions / files
$FileNames = @(
('{0}\functions\Get-WAUConfig.ps1' -f $WorkingDir),
('{0}\functions\Get-WAUCurrentVersion.ps1' -f $WorkingDir),
('{0}\functions\Get-WAUUpdateStatus.ps1' -f $WorkingDir),
('{0}\functions\Write-Log.ps1' -f $WorkingDir),
('{0}\Version.txt' -f $WorkingDir)
)
foreach ($FileName in $FileNames)
{
if (Test-Path -Path $FileName -ErrorAction SilentlyContinue)
{
$null = (Remove-Item -Path $FileName -Force -Confirm:$False -ErrorAction SilentlyContinue)
# log
Write-ToLog -LogMsg ('-> {0} removed.' -f $FileName) -LogColor 'green'
}
}
# Remove old registry key
$RegistryKeys = @(
'VersionMajor',
'VersionMinor'
)
foreach ($RegistryKey in $RegistryKeys)
{
if (Get-ItemProperty -Path $regPath -Name $RegistryKey -ErrorAction SilentlyContinue)
{
$null = (Remove-ItemProperty -Path $regPath -Name $RegistryKey -Force -Confirm:$False -ErrorAction SilentlyContinue)
}
}
# Reset WAU_UpdatePostActions Value
$null = ($WAUConfig | New-ItemProperty -Name WAU_PostUpdateActions -Value 0 -Force -Confirm:$False -ErrorAction SilentlyContinue)
# Get updated WAU Config
$Script:WAUConfig = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate')
# log
Write-ToLog -LogMsg 'Post Update actions finished' -LogColor 'green'
} }

View File

@ -1,65 +1,71 @@
# Initialisation # Initialisation
function Start-Init { function Start-Init
{
# Config console output encoding
[Console]::OutputEncoding = [Text.Encoding]::UTF8
#Config console output encoding # Workaround for ARM64 (Access Denied / Win32 internal Server error)
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $Script:ProgressPreference = 'SilentlyContinue'
$caller = ((Get-ChildItem -Path $MyInvocation.PSCommandPath).Name)
# Workaround for ARM64 (Access Denied / Win32 internal Server error) if ($caller -eq 'Winget-Upgrade.ps1')
$Script:ProgressPreference = 'SilentlyContinue' {
# Log Header
$Log = "`n##################################################`n# CHECK FOR APP UPDATES - $(Get-Date -Format (Get-Culture).DateTimeFormat.ShortDatePattern)`n##################################################"
$Log | Write-Host
# Logs initialisation
$Script:LogFile = ('{0}\logs\updates.log' -f $WorkingDir)
}
elseif ($caller -eq 'Winget-AutoUpdate-Install.ps1')
{
$Script:LogFile = ('{0}\logs\updates.log' -f $WingetUpdatePath)
}
$caller = Get-ChildItem $MyInvocation.PSCommandPath | Select-Object -Expand Name if (!(Test-Path -Path $LogFile -ErrorAction SilentlyContinue))
if ($caller -eq "Winget-Upgrade.ps1") { {
#Log Header # Create file if doesn't exist
$Log = "`n##################################################`n# CHECK FOR APP UPDATES - $(Get-Date -Format (Get-culture).DateTimeFormat.ShortDatePattern)`n##################################################" $null = (New-Item -ItemType File -Path $LogFile -Force -Confirm:$false)
$Log | Write-host # Set ACL for users on logfile
#Logs initialisation $NewAcl = (Get-Acl -Path $LogFile)
$Script:LogFile = "$WorkingDir\logs\updates.log" $identity = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList S-1-5-11)
} $fileSystemRights = 'Modify'
elseif ($caller -eq "Winget-AutoUpdate-Install.ps1") { $type = 'Allow'
$Script:LogFile = "$WingetUpdatePath\logs\updates.log" $fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type
} $fileSystemAccessRule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList)
$NewAcl.SetAccessRule($fileSystemAccessRule)
Set-Acl -Path $LogFile -AclObject $NewAcl
}
elseif ((Test-Path -Path $LogFile -ErrorAction SilentlyContinue) -and ($caller -eq 'Winget-AutoUpdate-Install.ps1'))
{
#Set ACL for users on logfile
$NewAcl = (Get-Acl -Path $LogFile)
$identity = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList S-1-5-11)
$fileSystemRights = 'Modify'
$type = 'Allow'
$fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type
$fileSystemAccessRule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList)
$NewAcl.SetAccessRule($fileSystemAccessRule)
$null = (Set-Acl -Path $LogFile -AclObject $NewAcl)
}
if (!(Test-Path $LogFile)) { # Check if Intune Management Extension Logs folder and WAU-updates.log exists, make symlink
#Create file if doesn't exist if ((Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs") -and !(Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log"))
New-Item -ItemType File -Path $LogFile -Force | Out-Null {
Write-Host -Object "`nCreating SymLink for log file (WAU-updates) in Intune Management Extension log folder" -ForegroundColor Yellow
$null = New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -ItemType SymbolicLink -Value $LogFile -Force -ErrorAction SilentlyContinue
}
#Set ACL for users on logfile # Check if Intune Management Extension Logs folder and WAU-install.log exists, make symlink
$NewAcl = Get-Acl -Path $LogFile if ((Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs" -ErrorAction SilentlyContinue) -and (Test-Path -Path ('{0}\logs\install.log' -f $WorkingDir) -ErrorAction SilentlyContinue) -and !(Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -ErrorAction SilentlyContinue))
$identity = New-Object System.Security.Principal.SecurityIdentifier S-1-5-11 {
$fileSystemRights = "Modify" Write-Host -Object "`nCreating SymLink for log file (WAU-install) in Intune Management Extension log folder" -ForegroundColor Yellow
$type = "Allow" $null = (New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -ItemType SymbolicLink -Value ('{0}\logs\install.log' -f $WorkingDir) -Force -ErrorAction SilentlyContinue)
$fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type }
$fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList
$NewAcl.SetAccessRule($fileSystemAccessRule)
Set-Acl -Path $LogFile -AclObject $NewAcl
}
elseif ((Test-Path $LogFile) -and ($caller -eq "Winget-AutoUpdate-Install.ps1")) {
#Set ACL for users on logfile
$NewAcl = Get-Acl -Path $LogFile
$identity = New-Object System.Security.Principal.SecurityIdentifier S-1-5-11
$fileSystemRights = "Modify"
$type = "Allow"
$fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type
$fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList
$NewAcl.SetAccessRule($fileSystemAccessRule)
Set-Acl -Path $LogFile -AclObject $NewAcl
}
#Check if Intune Management Extension Logs folder and WAU-updates.log exists, make symlink
if ((Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs") -and !(Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log")) {
Write-host "`nCreating SymLink for log file (WAU-updates) in Intune Management Extension log folder" -ForegroundColor Yellow
New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -ItemType SymbolicLink -Value $LogFile -Force -ErrorAction SilentlyContinue | Out-Null
}
#Check if Intune Management Extension Logs folder and WAU-install.log exists, make symlink
if ((Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs") -and (Test-Path "$WorkingDir\logs\install.log") -and !(Test-Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log")) {
Write-host "`nCreating SymLink for log file (WAU-install) in Intune Management Extension log folder" -ForegroundColor Yellow
New-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -ItemType SymbolicLink -Value "$WorkingDir\logs\install.log" -Force -ErrorAction SilentlyContinue | Out-Null
}
if ($caller -eq "Winget-Upgrade.ps1") {
#Log file
$Log | out-file -filepath $LogFile -Append
}
if ($caller -eq 'Winget-Upgrade.ps1')
{
# Log file
$Log | Out-File -FilePath $LogFile -Append -Force
}
} }

View File

@ -1,175 +1,192 @@
#Function to send the notifications to user # Function to send the notifications to user
function Start-NotifTask { function Start-NotifTask
{
[CmdletBinding()]
param (
[String]
$Title = 'Winget-AutoUpdate',
[String]
$Message,
[String]
$MessageType,
[String]
$Balise = 'WAU',
[String]
$OnClickAction,
[String]
$Body,
[String]
$Button1Text,
[String]
$Button1Action,
[Switch]
$ButtonDismiss = $false,
[Switch]
$UserRun = $false
)
param( if (($WAUConfig.WAU_NotificationLevel -eq 'Full') -or ($WAUConfig.WAU_NotificationLevel -eq 'SuccessOnly' -and $MessageType -eq 'Success') -or ($UserRun))
[String]$Title = "Winget-AutoUpdate", {
[String]$Message, # XML Toast template creation
[String]$MessageType, [xml]$ToastTemplate = New-Object -TypeName system.Xml.XmlDocument
[String]$Balise = "WAU", $ToastTemplate.LoadXml("<?xml version=`"1.0`" encoding=`"utf-8`"?><toast></toast>")
[String]$OnClickAction,
[String]$Body,
[String]$Button1Text,
[String]$Button1Action,
[Switch]$ButtonDismiss = $false,
[Switch]$UserRun = $false
)
if (($WAUConfig.WAU_NotificationLevel -eq "Full") -or ($WAUConfig.WAU_NotificationLevel -eq "SuccessOnly" -and $MessageType -eq "Success") -or ($UserRun)) { # Creation of visual node
$XMLvisual = $ToastTemplate.CreateElement('visual')
# XML Toast template creation # Creation of a binding node
[xml]$ToastTemplate = New-Object system.Xml.XmlDocument $XMLbinding = $ToastTemplate.CreateElement('binding')
$ToastTemplate.LoadXml("<?xml version=`"1.0`" encoding=`"utf-8`"?><toast></toast>") $null = $XMLvisual.AppendChild($XMLbinding)
$XMLbindingAtt1 = ($ToastTemplate.CreateAttribute('template'))
$XMLbindingAtt1.Value = 'ToastGeneric'
$null = $XMLbinding.Attributes.Append($XMLbindingAtt1)
# Creation of visual node $XMLimagepath = ('{0}\icons\{1}.png' -f $WorkingDir, $MessageType)
$XMLvisual = $ToastTemplate.CreateElement("visual") if (Test-Path -Path $XMLimagepath -ErrorAction SilentlyContinue)
{
# Creation of a image node
$XMLimage = $ToastTemplate.CreateElement('image')
$null = $XMLbinding.AppendChild($XMLimage)
$XMLimageAtt1 = $ToastTemplate.CreateAttribute('placement')
$XMLimageAtt1.Value = 'appLogoOverride'
$null = $XMLimage.Attributes.Append($XMLimageAtt1)
$XMLimageAtt2 = $ToastTemplate.CreateAttribute('src')
$XMLimageAtt2.Value = ('{0}\icons\{1}.png' -f $WorkingDir, $MessageType)
$null = $XMLimage.Attributes.Append($XMLimageAtt2)
}
# Creation of a binding node if ($Title)
$XMLbinding = $ToastTemplate.CreateElement("binding") {
$XMLvisual.AppendChild($XMLbinding) | Out-Null # Creation of a text node
$XMLbindingAtt1 = ($ToastTemplate.CreateAttribute("template")) $XMLtitle = $ToastTemplate.CreateElement('text')
$XMLbindingAtt1.Value = "ToastGeneric" $XMLtitleText = $ToastTemplate.CreateTextNode($Title)
$XMLbinding.Attributes.Append($XMLbindingAtt1) | Out-Null $null = $XMLtitle.AppendChild($XMLtitleText)
$null = $XMLbinding.AppendChild($XMLtitle)
}
$XMLimagepath = "$WorkingDir\icons\$MessageType.png" if ($Message)
if (Test-Path $XMLimagepath) { {
# Creation of a image node # Creation of a text node
$XMLimage = $ToastTemplate.CreateElement("image") $XMLtext = $ToastTemplate.CreateElement('text')
$XMLbinding.AppendChild($XMLimage) | Out-Null $XMLtextText = $ToastTemplate.CreateTextNode($Message)
$XMLimageAtt1 = $ToastTemplate.CreateAttribute("placement") $null = $XMLtext.AppendChild($XMLtextText)
$XMLimageAtt1.Value = "appLogoOverride" $null = $XMLbinding.AppendChild($XMLtext)
$XMLimage.Attributes.Append($XMLimageAtt1) | Out-Null }
$XMLimageAtt2 = $ToastTemplate.CreateAttribute("src")
$XMLimageAtt2.Value = "$WorkingDir\icons\$MessageType.png"
$XMLimage.Attributes.Append($XMLimageAtt2) | Out-Null
}
if ($Title) { if ($Body)
# Creation of a text node {
$XMLtitle = $ToastTemplate.CreateElement("text") # Creation of a group node
$XMLtitleText = $ToastTemplate.CreateTextNode($Title) $XMLgroup = $ToastTemplate.CreateElement('group')
$XMLtitle.AppendChild($XMLtitleText) | Out-Null $null = $XMLbinding.AppendChild($XMLgroup)
$XMLbinding.AppendChild($XMLtitle) | Out-Null
}
if ($Message) { # Creation of a subgroup node
# Creation of a text node $XMLsubgroup = $ToastTemplate.CreateElement('subgroup')
$XMLtext = $ToastTemplate.CreateElement("text") $null = $XMLgroup.AppendChild($XMLsubgroup)
$XMLtextText = $ToastTemplate.CreateTextNode($Message)
$XMLtext.AppendChild($XMLtextText) | Out-Null
$XMLbinding.AppendChild($XMLtext) | Out-Null
}
if ($Body) { # Creation of a text node
# Creation of a group node $XMLcontent = $ToastTemplate.CreateElement('text')
$XMLgroup = $ToastTemplate.CreateElement("group") $XMLcontentText = $ToastTemplate.CreateTextNode($Body)
$XMLbinding.AppendChild($XMLgroup) | Out-Null $null = $XMLcontent.AppendChild($XMLcontentText)
$null = $XMLsubgroup.AppendChild($XMLcontent)
$XMLcontentAtt1 = $ToastTemplate.CreateAttribute('hint-style')
$XMLcontentAtt1.Value = 'body'
$null = $XMLcontent.Attributes.Append($XMLcontentAtt1)
$XMLcontentAtt2 = $ToastTemplate.CreateAttribute('hint-wrap')
$XMLcontentAtt2.Value = 'true'
$null = $XMLcontent.Attributes.Append($XMLcontentAtt2)
}
# Creation of a subgroup node # Creation of actions node
$XMLsubgroup = $ToastTemplate.CreateElement("subgroup") $XMLactions = $ToastTemplate.CreateElement('actions')
$XMLgroup.AppendChild($XMLsubgroup) | Out-Null
# Creation of a text node if ($Button1Text)
$XMLcontent = $ToastTemplate.CreateElement("text") {
$XMLcontentText = $ToastTemplate.CreateTextNode($Body) # Creation of action node
$XMLcontent.AppendChild($XMLcontentText) | Out-Null $XMLaction = $ToastTemplate.CreateElement('action')
$XMLsubgroup.AppendChild($XMLcontent) | Out-Null $null = $XMLactions.AppendChild($XMLaction)
$XMLcontentAtt1 = $ToastTemplate.CreateAttribute("hint-style") $XMLactionAtt1 = $ToastTemplate.CreateAttribute('content')
$XMLcontentAtt1.Value = "body" $XMLactionAtt1.Value = $Button1Text
$XMLcontent.Attributes.Append($XMLcontentAtt1) | Out-Null $null = $XMLaction.Attributes.Append($XMLactionAtt1)
$XMLcontentAtt2 = $ToastTemplate.CreateAttribute("hint-wrap") if ($Button1Action)
$XMLcontentAtt2.Value = "true" {
$XMLcontent.Attributes.Append($XMLcontentAtt2) | Out-Null $XMLactionAtt2 = $ToastTemplate.CreateAttribute('arguments')
} $XMLactionAtt2.Value = $Button1Action
$null = $XMLaction.Attributes.Append($XMLactionAtt2)
$XMLactionAtt3 = $ToastTemplate.CreateAttribute('activationType')
$XMLactionAtt3.Value = 'Protocol'
$null = $XMLaction.Attributes.Append($XMLactionAtt3)
}
}
# Creation of actions node if ($ButtonDismiss)
$XMLactions = $ToastTemplate.CreateElement("actions") {
# Creation of action node
$XMLaction = $ToastTemplate.CreateElement('action')
$null = $XMLactions.AppendChild($XMLaction)
$XMLactionAtt1 = $ToastTemplate.CreateAttribute('content')
$XMLactionAtt1.Value = ''
$null = $XMLaction.Attributes.Append($XMLactionAtt1)
$XMLactionAtt2 = $ToastTemplate.CreateAttribute('arguments')
$XMLactionAtt2.Value = 'dismiss'
$null = $XMLaction.Attributes.Append($XMLactionAtt2)
$XMLactionAtt3 = $ToastTemplate.CreateAttribute('activationType')
$XMLactionAtt3.Value = 'system'
$null = $XMLaction.Attributes.Append($XMLactionAtt3)
}
if ($Button1Text) { # Creation of tag node
# Creation of action node $XMLtag = $ToastTemplate.CreateElement('tag')
$XMLaction = $ToastTemplate.CreateElement("action") $XMLtagText = $ToastTemplate.CreateTextNode($Balise)
$XMLactions.AppendChild($XMLaction) | Out-Null $null = $XMLtag.AppendChild($XMLtagText)
$XMLactionAtt1 = $ToastTemplate.CreateAttribute("content")
$XMLactionAtt1.Value = $Button1Text
$XMLaction.Attributes.Append($XMLactionAtt1) | Out-Null
if ($Button1Action) {
$XMLactionAtt2 = $ToastTemplate.CreateAttribute("arguments")
$XMLactionAtt2.Value = $Button1Action
$XMLaction.Attributes.Append($XMLactionAtt2) | Out-Null
$XMLactionAtt3 = $ToastTemplate.CreateAttribute("activationType")
$XMLactionAtt3.Value = "Protocol"
$XMLaction.Attributes.Append($XMLactionAtt3) | Out-Null
}
}
if ($ButtonDismiss) { # Add the visual node to the xml
# Creation of action node $null = $ToastTemplate.LastChild.AppendChild($XMLvisual)
$XMLaction = $ToastTemplate.CreateElement("action") $null = $ToastTemplate.LastChild.AppendChild($XMLactions)
$XMLactions.AppendChild($XMLaction) | Out-Null $null = $ToastTemplate.LastChild.AppendChild($XMLtag)
$XMLactionAtt1 = $ToastTemplate.CreateAttribute("content")
$XMLactionAtt1.Value = ""
$XMLaction.Attributes.Append($XMLactionAtt1) | Out-Null
$XMLactionAtt2 = $ToastTemplate.CreateAttribute("arguments")
$XMLactionAtt2.Value = "dismiss"
$XMLaction.Attributes.Append($XMLactionAtt2) | Out-Null
$XMLactionAtt3 = $ToastTemplate.CreateAttribute("activationType")
$XMLactionAtt3.Value = "system"
$XMLaction.Attributes.Append($XMLactionAtt3) | Out-Null
}
# Creation of tag node if ($OnClickAction)
$XMLtag = $ToastTemplate.CreateElement("tag") {
$XMLtagText = $ToastTemplate.CreateTextNode($Balise) $null = $ToastTemplate.toast.SetAttribute('activationType', 'Protocol')
$XMLtag.AppendChild($XMLtagText) | Out-Null $null = $ToastTemplate.toast.SetAttribute('launch', $OnClickAction)
}
# Add the visual node to the xml # if not "Interactive" user, run as system
$ToastTemplate.LastChild.AppendChild($XMLvisual) | Out-Null if ($IsSystem)
$ToastTemplate.LastChild.AppendChild($XMLactions) | Out-Null {
$ToastTemplate.LastChild.AppendChild($XMLtag) | Out-Null # Save XML to File
$ToastTemplateLocation = ('{0}\config\' -f $WAUConfig.InstallLocation)
if (!(Test-Path -Path $ToastTemplateLocation -ErrorAction SilentlyContinue))
{
$null = (New-Item -ItemType Directory -Force -Confirm:$false -Path $ToastTemplateLocation)
}
if ($OnClickAction) { $ToastTemplate.Save(('{0}\notif.xml' -f $ToastTemplateLocation))
$ToastTemplate.toast.SetAttribute("activationType", "Protocol") | Out-Null
$ToastTemplate.toast.SetAttribute("launch", $OnClickAction) | Out-Null
}
#if not "Interactive" user, run as system # Run Notify scheduled task to notify conneted users
if ($IsSystem) { $null = (Get-ScheduledTask -TaskName 'Winget-AutoUpdate-Notify' -ErrorAction SilentlyContinue | Start-ScheduledTask -ErrorAction SilentlyContinue)
}
else
{
#else, run as connected user
# Load Assemblies
$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
#Save XML to File # Prepare XML
$ToastTemplateLocation = "$($WAUConfig.InstallLocation)\config\" $ToastXml = [Windows.Data.Xml.Dom.XmlDocument]::New()
if (!(Test-Path $ToastTemplateLocation)) { $ToastXml.LoadXml($ToastTemplate.OuterXml)
New-Item -ItemType Directory -Force -Path $ToastTemplateLocation
}
$ToastTemplate.Save("$ToastTemplateLocation\notif.xml")
#Run Notify scheduled task to notify conneted users # Specify Launcher App ID
Get-ScheduledTask -TaskName "Winget-AutoUpdate-Notify" -ErrorAction SilentlyContinue | Start-ScheduledTask -ErrorAction SilentlyContinue $LauncherID = 'Windows.SystemToast.Winget.Notification'
} # Prepare and Create Toast
#else, run as connected user $ToastMessage = [Windows.UI.Notifications.ToastNotification]::New($ToastXml)
else { $ToastMessage.Tag = $ToastTemplate.toast.tag
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($LauncherID).Show($ToastMessage)
#Load Assemblies }
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
#Prepare XML
$ToastXml = [Windows.Data.Xml.Dom.XmlDocument]::New()
$ToastXml.LoadXml($ToastTemplate.OuterXml)
#Specify Launcher App ID
$LauncherID = "Windows.SystemToast.Winget.Notification"
#Prepare and Create Toast
$ToastMessage = [Windows.UI.Notifications.ToastNotification]::New($ToastXml)
$ToastMessage.Tag = $ToastTemplate.toast.tag
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($LauncherID).Show($ToastMessage)
}
#Wait for notification to display
Start-Sleep 3
}
# Wait for notification to display
Start-Sleep -Seconds 3
}
} }

View File

@ -1,83 +1,121 @@
#Function to check Block/Allow List External Path # Function to check Block/Allow List External Path
function Test-ListPath ($ListPath, $UseWhiteList, $WingetUpdatePath) { function Test-ListPath
# URL, UNC or Local Path {
if ($UseWhiteList) { # URL, UNC or Local Path
$ListType = "included_apps.txt" [CmdletBinding()]
} param
else { (
$ListType = "excluded_apps.txt" [string]
} $ListPath,
[string]
$UseWhiteList,
[string]
$WingetUpdatePath
)
# Get local and external list paths if ($UseWhiteList)
$LocalList = -join ($WingetUpdatePath, "\", $ListType) {
$ExternalList = -join ($ListPath, "\", $ListType) $ListType = 'included_apps.txt'
}
else
{
$ListType = 'excluded_apps.txt'
}
# Check if a list exists # Get local and external list paths
if (Test-Path "$LocalList") { $LocalList = -join ($WingetUpdatePath, '\', $ListType)
$dateLocal = (Get-Item "$LocalList").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") $ExternalList = -join ($ListPath, '\', $ListType)
}
# If path is URL # Check if a list exists
if ($ListPath -like "http*") { if (Test-Path -Path $LocalList -ErrorAction SilentlyContinue)
$ExternalList = -join ($ListPath, "/", $ListType) {
$wc = New-Object System.Net.WebClient $dateLocal = (Get-Item -Path $LocalList).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
try { }
$wc.OpenRead("$ExternalList").Close() | Out-Null
$dateExternal = ([DateTime]$wc.ResponseHeaders['Last-Modified']).ToString("yyyy-MM-dd HH:mm:ss") # If path is URL
if ($dateExternal -gt $dateLocal) { if ($ListPath -like 'http*')
try { {
$wc.DownloadFile($ExternalList, $LocalList) $ExternalList = -join ($ListPath, '/', $ListType)
} $wc = (New-Object -TypeName System.Net.WebClient)
catch {
$Script:ReachNoPath = $True try
return $False {
} $null = $wc.OpenRead($ExternalList).Close()
return $true $dateExternal = ([DateTime]$wc.ResponseHeaders['Last-Modified']).ToString('yyyy-MM-dd HH:mm:ss')
if ($dateExternal -gt $dateLocal)
{
try
{
$wc.DownloadFile($ExternalList, $LocalList)
} }
} catch
catch { {
try { $Script:ReachNoPath = $True
$content = $wc.DownloadString("$ExternalList") return $False
if ($null -ne $content -and $content -match "\w\.\w") {
$wc.DownloadFile($ExternalList, $LocalList)
return $true
}
else {
$Script:ReachNoPath = $True
return $False
}
} }
catch { return $True
$Script:ReachNoPath = $True }
return $False }
catch
{
try
{
$content = $wc.DownloadString(('{0}' -f $ExternalList))
if ($null -ne $content -and $content -match '\w\.\w')
{
$wc.DownloadFile($ExternalList, $LocalList)
return $True
} }
} else
} {
# If path is UNC or local $Script:ReachNoPath = $True
else { return $False
if (Test-Path -Path $ExternalList) {
try {
$dateExternal = (Get-Item "$ExternalList").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
} }
catch { }
$Script:ReachNoPath = $True catch
return $False {
}
if ($dateExternal -gt $dateLocal) {
try {
Copy-Item $ExternalList -Destination $LocalList -Force
}
catch {
$Script:ReachNoPath = $True
return $False
}
return $True
}
}
else {
$Script:ReachNoPath = $True $Script:ReachNoPath = $True
} return $False
return $False }
} }
}
else
{
# If path is UNC or local
if (Test-Path -Path $ExternalList)
{
try
{
$dateExternal = (Get-Item -Path ('{0}' -f $ExternalList)).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
}
catch
{
$Script:ReachNoPath = $True
return $False
}
if ($dateExternal -gt $dateLocal)
{
try
{
Copy-Item -Path $ExternalList -Destination $LocalList -Force
}
catch
{
$Script:ReachNoPath = $True
return $False
}
return $True
}
}
else
{
$Script:ReachNoPath = $True
}
return $False
}
} }

View File

@ -1,34 +1,50 @@
#Function to check if modification exists within 'mods' directory # Function to check if modification exists within 'mods' directory
function Test-Mods ($app) { function Test-Mods
{
# Takes care of a null situation
[CmdletBinding()]
param
(
[string]
$app
)
#Takes care of a null situation $ModsPreInstall = $null
$ModsPreInstall = $null $ModsOverride = $null
$ModsOverride = $null $ModsUpgrade = $null
$ModsUpgrade = $null $ModsInstall = $null
$ModsInstall = $null $ModsInstalled = $null
$ModsInstalled = $null $Mods = ('{0}\mods' -f $WorkingDir)
$Mods = "$WorkingDir\mods" if (Test-Path -Path ('{0}\{1}-*' -f $Mods, $app) -ErrorAction SilentlyContinue)
if (Test-Path "$Mods\$app-*") { {
if (Test-Path "$Mods\$app-preinstall.ps1") { if (Test-Path -Path ('{0}\{1}-preinstall.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue)
$ModsPreInstall = "$Mods\$app-preinstall.ps1" {
} $ModsPreInstall = ('{0}\{1}-preinstall.ps1' -f $Mods, $app)
if (Test-Path "$Mods\$app-override.txt") { }
$ModsOverride = Get-Content "$Mods\$app-override.txt" -Raw
}
if (Test-Path "$Mods\$app-install.ps1") {
$ModsInstall = "$Mods\$app-install.ps1"
$ModsUpgrade = "$Mods\$app-install.ps1"
}
if (Test-Path "$Mods\$app-upgrade.ps1") {
$ModsUpgrade = "$Mods\$app-upgrade.ps1"
}
if (Test-Path "$Mods\$app-installed.ps1") {
$ModsInstalled = "$Mods\$app-installed.ps1"
}
}
return $ModsPreInstall, $ModsOverride, $ModsUpgrade, $ModsInstall, $ModsInstalled if (Test-Path -Path ('{0}\{1}-override.txt' -f $Mods, $app) -ErrorAction SilentlyContinue)
{
$ModsOverride = Get-Content -Path ('{0}\{1}-override.txt' -f $Mods, $app) -Raw
}
if (Test-Path -Path ('{0}\{1}-install.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue)
{
$ModsInstall = ('{0}\{1}-install.ps1' -f $Mods, $app)
$ModsUpgrade = ('{0}\{1}-install.ps1' -f $Mods, $app)
}
if (Test-Path -Path ('{0}\{1}-upgrade.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue)
{
$ModsUpgrade = ('{0}\{1}-upgrade.ps1' -f $Mods, $app)
}
if (Test-Path -Path ('{0}\{1}-installed.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue)
{
$ModsInstalled = ('{0}\{1}-installed.ps1' -f $Mods, $app)
}
}
return $ModsPreInstall, $ModsOverride, $ModsUpgrade, $ModsInstall, $ModsInstalled
} }

View File

@ -1,233 +1,310 @@
#Function to check mods External Path #Function to check mods External Path
function Test-ModsPath ($ModsPath, $WingetUpdatePath, $AzureBlobSASURL) { function Test-ModsPath
# URL, UNC or Local Path {
# Get local and external Mods paths # URL, UNC or Local Path
$LocalMods = -join ($WingetUpdatePath, "\", "mods") # Get local and external Mods paths
$ExternalMods = "$ModsPath"
#Get File Names Locally [CmdletBinding()]
$InternalModsNames = Get-ChildItem -Path $LocalMods -Name -Recurse -Include *.ps1, *.txt param
$InternalBinsNames = Get-ChildItem -Path $LocalMods"\bins" -Name -Recurse -Include *.exe (
[string]
$ModsPath,
[string]
$WingetUpdatePath,
[string]
$AzureBlobSASURL
)
$LocalMods = -join ($WingetUpdatePath, '\', 'mods')
$ExternalMods = $ModsPath
# If path is URL # Get File Names Locally
if ($ExternalMods -like "http*") { $InternalModsNames = (Get-ChildItem -Path $LocalMods -Name -Recurse -Include *.ps1, *.txt -ErrorAction SilentlyContinue)
# enable TLS 1.2 and TLS 1.1 protocols $InternalBinsNames = (Get-ChildItem -Path $LocalMods"\bins" -Name -Recurse -Include *.exe -ErrorAction SilentlyContinue)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls11
#Get Index of $ExternalMods (or index page with href listing of all the Mods)
try {
$WebResponse = Invoke-WebRequest -Uri $ExternalMods -UseBasicParsing
}
catch {
$Script:ReachNoPath = $True
return $False
}
#Check for bins, download if newer. Delete if not external # If path is URL
$ExternalBins = "$ModsPath/bins" if ($ExternalMods -like 'http*')
if ($WebResponse -match "bins/") { {
$BinResponse = Invoke-WebRequest -Uri $ExternalBins -UseBasicParsing # enable TLS 1.2 and TLS 1.1 protocols
# Collect the external list of href links [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls11
$BinLinks = $BinResponse.Links | Select-Object -ExpandProperty HREF # Get Index of $ExternalMods (or index page with href listing of all the Mods)
#If there's a directory path in the HREF:s, delete it (IIS) try
$CleanBinLinks = $BinLinks -replace "/.*/", "" {
#Modify strings to HREF:s $WebResponse = (Invoke-WebRequest -Uri $ExternalMods -UseBasicParsing)
$index = 0 }
foreach ($Bin in $CleanBinLinks) { catch
if ($Bin) { {
$CleanBinLinks[$index] = '<a href="' + $Bin + '"> ' + $Bin + '</a>' $Script:ReachNoPath = $True
}
$index++
}
#Delete Local Bins that don't exist Externally
$index = 0
$CleanLinks = $BinLinks -replace "/.*/", ""
foreach ($Bin in $InternalBinsNames) {
If ($CleanLinks -notcontains "$Bin") {
Remove-Item $LocalMods\bins\$Bin -Force -ErrorAction SilentlyContinue | Out-Null
}
$index++
}
$CleanBinLinks = $BinLinks -replace "/.*/", ""
$Bin = ""
#Loop through all links
$wc = New-Object System.Net.WebClient
$CleanBinLinks | ForEach-Object {
#Check for .exe in listing/HREF:s in an index page pointing to .exe
if ($_ -like "*.exe") {
$dateExternalBin = ""
$dateLocalBin = ""
$wc.OpenRead("$ExternalBins/$_").Close() | Out-Null
$dateExternalBin = ([DateTime]$wc.ResponseHeaders['Last-Modified']).ToString("yyyy-MM-dd HH:mm:ss")
if (Test-Path -Path $LocalMods"\bins\"$_) {
$dateLocalBin = (Get-Item "$LocalMods\bins\$_").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
}
if ($dateExternalBin -gt $dateLocalBin) {
$SaveBin = Join-Path -Path "$LocalMods\bins" -ChildPath $_
Invoke-WebRequest -Uri "$ExternalBins/$_" -OutFile $SaveBin.Replace("%20", " ") -UseBasicParsing
}
}
}
}
# Collect the external list of href links return $False
$ModLinks = $WebResponse.Links | Select-Object -ExpandProperty HREF }
#If there's a directory path in the HREF:s, delete it (IIS) # Check for bins, download if newer. Delete if not external
$CleanLinks = $ModLinks -replace "/.*/", "" $ExternalBins = ('{0}/bins' -f $ModsPath)
#Modify strings to HREF:s if ($WebResponse -match 'bins/')
$index = 0 {
foreach ($Mod in $CleanLinks) { $BinResponse = Invoke-WebRequest -Uri $ExternalBins -UseBasicParsing
if ($Mod) { # Collect the external list of href links
$CleanLinks[$index] = '<a href="' + $Mod + '"> ' + $Mod + '</a>' $BinLinks = $BinResponse.Links | Select-Object -ExpandProperty HREF
# If there's a directory path in the HREF:s, delete it (IIS)
$CleanBinLinks = $BinLinks -replace '/.*/', ''
# Modify strings to HREF:s
$index = 0
foreach ($Bin in $CleanBinLinks)
{
if ($Bin)
{
$CleanBinLinks[$index] = '<a href="' + $Bin + '"> ' + $Bin + '</a>'
} }
$index++ $index++
} }
#Delete Local Mods that don't exist Externally # Delete Local Bins that don't exist Externally
$DeletedMods = 0 $index = 0
$index = 0 $CleanLinks = $BinLinks -replace '/.*/', ''
$CleanLinks = $ModLinks -replace "/.*/", ""
foreach ($Mod in $InternalModsNames) { foreach ($Bin in $InternalBinsNames)
If ($CleanLinks -notcontains "$Mod") { {
Remove-Item $LocalMods\$Mod -Force -ErrorAction SilentlyContinue | Out-Null if ($CleanLinks -notcontains $Bin)
$DeletedMods++ {
$null = (Remove-Item -Path $LocalMods\bins\$Bin -Force -Confirm:$False -ErrorAction SilentlyContinue)
} }
$index++ $index++
} }
$CleanLinks = $ModLinks -replace "/.*/", "" $CleanBinLinks = $BinLinks -replace '/.*/', ''
$Bin = ''
# Loop through all links
$wc = New-Object -TypeName System.Net.WebClient
$CleanBinLinks | ForEach-Object -Process {
# Check for .exe in listing/HREF:s in an index page pointing to .exe
if ($_ -like '*.exe')
{
$dateExternalBin = ''
$dateLocalBin = ''
$null = $wc.OpenRead(('{0}/{1}' -f $ExternalBins, $_)).Close()
$dateExternalBin = ([DateTime]$wc.ResponseHeaders['Last-Modified']).ToString('yyyy-MM-dd HH:mm:ss')
#Loop through all links if (Test-Path -Path $LocalMods"\bins\"$_)
$wc = New-Object System.Net.WebClient {
$CleanLinks | ForEach-Object { $dateLocalBin = (Get-Item -Path ('{0}\bins\{1}' -f $LocalMods, $_)).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
#Check for .ps1/.txt in listing/HREF:s in an index page pointing to .ps1/.txt }
if (($_ -like "*.ps1") -or ($_ -like "*.txt")) {
try {
$dateExternalMod = ""
$dateLocalMod = ""
$wc.OpenRead("$ExternalMods/$_").Close() | Out-Null
$dateExternalMod = ([DateTime]$wc.ResponseHeaders['Last-Modified']).ToString("yyyy-MM-dd HH:mm:ss")
if (Test-Path -Path $LocalMods"\"$_) {
$dateLocalMod = (Get-Item "$LocalMods\$_").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
}
if ($dateExternalMod -gt $dateLocalMod) { if ($dateExternalBin -gt $dateLocalBin)
try { {
$SaveMod = Join-Path -Path "$LocalMods\" -ChildPath $_ $SaveBin = Join-Path -Path ('{0}\bins' -f $LocalMods) -ChildPath $_
$Mod = '{0}/{1}' -f $ModsPath.TrimEnd('/'), $_ Invoke-WebRequest -Uri ('{0}/{1}' -f $ExternalBins, $_) -OutFile $SaveBin.Replace('%20', ' ') -UseBasicParsing
Invoke-WebRequest -Uri "$Mod" -OutFile $SaveMod -UseBasicParsing }
$ModsUpdated++
}
catch {
$Script:ReachNoPath = $True
}
}
}
catch {
if (($_ -like "*.ps1") -or ($_ -like "*.txt")) {
$Script:ReachNoPath = $True
}
}
} }
} }
return $ModsUpdated, $DeletedMods }
}
# If Path is Azure Blob
elseif ($ExternalMods -like "AzureBlob") {
Write-ToLog "Azure Blob Storage set as mod source"
Write-ToLog "Checking AZCopy"
Get-AZCopy $WingetUpdatePath
#Safety check to make sure we really do have azcopy.exe and a Blob URL
if ((Test-Path -Path "$WingetUpdatePath\azcopy.exe" -PathType Leaf) -and ($null -ne $AzureBlobSASURL)) {
Write-ToLog "Syncing Blob storage with local storage"
$AZCopySyncOutput = & $WingetUpdatePath\azcopy.exe sync "$AzureBlobSASURL" "$LocalMods" --from-to BlobLocal --delete-destination=true # Collect the external list of href links
$AZCopyOutputLines = $AZCopySyncOutput.Split([Environment]::NewLine) $ModLinks = $WebResponse.Links | Select-Object -ExpandProperty HREF
# If there's a directory path in the HREF:s, delete it (IIS)
$CleanLinks = $ModLinks -replace '/.*/', ''
# Modify strings to HREF:s
$index = 0
foreach ( $_ in $AZCopyOutputLines) { foreach ($Mod in $CleanLinks)
$AZCopySyncAdditionsRegex = [regex]::new("(?<=Number of Copy Transfers Completed:\s+)\d+") {
$AZCopySyncDeletionsRegex = [regex]::new("(?<=Number of Deletions at Destination:\s+)\d+") if ($Mod)
$AZCopySyncErrorRegex = [regex]::new("^Cannot perform sync due to error:") {
$CleanLinks[$index] = '<a href="' + $Mod + '"> ' + $Mod + '</a>'
}
$index++
}
$AZCopyAdditions = [int] $AZCopySyncAdditionsRegex.Match($_).Value # Delete Local Mods that don't exist Externally
$AZCopyDeletions = [int] $AZCopySyncDeletionsRegex.Match($_).Value $DeletedMods = 0
$index = 0
$CleanLinks = $ModLinks -replace '/.*/', ''
if ($AZCopyAdditions -ne 0) { foreach ($Mod in $InternalModsNames)
$ModsUpdated = $AZCopyAdditions {
} if ($CleanLinks -notcontains $Mod)
{
$null = (Remove-Item -Path $LocalMods\$Mod -Force -Confirm:$False -ErrorAction SilentlyContinue)
$DeletedMods++
}
$index++
}
if ($AZCopyDeletions -ne 0) { $CleanLinks = $ModLinks -replace '/.*/', ''
$DeletedMods = $AZCopyDeletions
}
if ($AZCopySyncErrorRegex.Match($_).Value) { # Loop through all links
Write-ToLog "AZCopy Sync Error! $_"
} $CleanLinks | ForEach-Object -Process {
# Check for .ps1/.txt in listing/HREF:s in an index page pointing to .ps1/.txt
if (($_ -like '*.ps1') -or ($_ -like '*.txt'))
{
try
{
$dateExternalMod = ''
$dateLocalMod = ''
$null = $wc.OpenRead(('{0}/{1}' -f $ExternalMods, $_)).Close()
$dateExternalMod = ([DateTime]$wc.ResponseHeaders['Last-Modified']).ToString('yyyy-MM-dd HH:mm:ss')
if (Test-Path -Path $LocalMods"\"$_)
{
$dateLocalMod = (Get-Item -Path ('{0}\{1}' -f $LocalMods, $_)).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
}
if ($dateExternalMod -gt $dateLocalMod)
{
try
{
$SaveMod = Join-Path -Path ('{0}\' -f $LocalMods) -ChildPath $_
$Mod = '{0}/{1}' -f $ModsPath.TrimEnd('/'), $_
$null = (Invoke-WebRequest -Uri $Mod -OutFile $SaveMod -UseBasicParsing)
$ModsUpdated++
}
catch
{
$Script:ReachNoPath = $True
}
}
} }
} catch
else { {
Write-ToLog "Error 'azcopy.exe' or SAS Token not found!" if (($_ -like '*.ps1') -or ($_ -like '*.txt'))
} {
$Script:ReachNoPath = $True
return $ModsUpdated, $DeletedMods }
}
# If path is UNC or local
else {
$ExternalBins = "$ModsPath\bins"
if (Test-Path -Path $ExternalBins"\*.exe") {
$ExternalBinsNames = Get-ChildItem -Path $ExternalBins -Name -Recurse -Include *.exe
#Delete Local Bins that don't exist Externally
foreach ($Bin in $InternalBinsNames) {
If ($Bin -notin $ExternalBinsNames ) {
Remove-Item $LocalMods\bins\$Bin -Force -ErrorAction SilentlyContinue | Out-Null
}
} }
#Copy newer external bins }
foreach ($Bin in $ExternalBinsNames) { }
$dateExternalBin = "" return $ModsUpdated, $DeletedMods
$dateLocalBin = "" }
if (Test-Path -Path $LocalMods"\bins\"$Bin) { # If Path is Azure Blob
$dateLocalBin = (Get-Item "$LocalMods\bins\$Bin").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") elseif ($ExternalMods -like 'AzureBlob')
} {
$dateExternalBin = (Get-Item "$ExternalBins\$Bin").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") Write-ToLog -LogMsg 'Azure Blob Storage set as mod source'
if ($dateExternalBin -gt $dateLocalBin) { Write-ToLog -LogMsg 'Checking AZCopy'
Copy-Item $ExternalBins\$Bin -Destination $LocalMods\bins\$Bin -Force -ErrorAction SilentlyContinue | Out-Null Get-AZCopy $WingetUpdatePath
}
}
}
if ((Test-Path -Path $ExternalMods"\*.ps1") -or (Test-Path -Path $ExternalMods"\*.txt")) { # Safety check to make sure we really do have azcopy.exe and a Blob URL
#Get File Names Externally if ((Test-Path -Path ('{0}\azcopy.exe' -f $WingetUpdatePath) -PathType Leaf) -and ($null -ne $AzureBlobSASURL))
$ExternalModsNames = Get-ChildItem -Path $ExternalMods -Name -Recurse -Include *.ps1, *.txt {
Write-ToLog -LogMsg 'Syncing Blob storage with local storage'
#Delete Local Mods that don't exist Externally $AZCopySyncOutput = & $WingetUpdatePath\azcopy.exe sync $AzureBlobSASURL $LocalMods --from-to BlobLocal --delete-destination=true
$DeletedMods = 0 $AZCopyOutputLines = $AZCopySyncOutput.Split([Environment]::NewLine)
foreach ($Mod in $InternalModsNames) {
If ($Mod -notin $ExternalModsNames ) { foreach ($_ in $AZCopyOutputLines)
Remove-Item $LocalMods\$Mod -Force -ErrorAction SilentlyContinue | Out-Null {
$DeletedMods++ $AZCopySyncAdditionsRegex = [regex]::new('(?<=Number of Copy Transfers Completed:\s+)\d+')
} $AZCopySyncDeletionsRegex = [regex]::new('(?<=Number of Deletions at Destination:\s+)\d+')
$AZCopySyncErrorRegex = [regex]::new('^Cannot perform sync due to error:')
$AZCopyAdditions = [int]$AZCopySyncAdditionsRegex.Match($_).Value
$AZCopyDeletions = [int]$AZCopySyncDeletionsRegex.Match($_).Value
if ($AZCopyAdditions -ne 0)
{
$ModsUpdated = $AZCopyAdditions
} }
#Copy newer external mods if ($AZCopyDeletions -ne 0)
foreach ($Mod in $ExternalModsNames) { {
$dateExternalMod = "" $DeletedMods = $AZCopyDeletions
$dateLocalMod = ""
if (Test-Path -Path $LocalMods"\"$Mod) {
$dateLocalMod = (Get-Item "$LocalMods\$Mod").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
}
$dateExternalMod = (Get-Item "$ExternalMods\$Mod").LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
if ($dateExternalMod -gt $dateLocalMod) {
Copy-Item $ExternalMods\$Mod -Destination $LocalMods\$Mod -Force -ErrorAction SilentlyContinue | Out-Null
$ModsUpdated++
}
} }
}
else { if ($AZCopySyncErrorRegex.Match($_).Value)
$Script:ReachNoPath = $True {
} Write-ToLog -LogMsg ('AZCopy Sync Error! {0}' -f $_)
return $ModsUpdated, $DeletedMods }
} }
}
else
{
Write-ToLog -LogMsg "Error 'azcopy.exe' or SAS Token not found!"
}
return $ModsUpdated, $DeletedMods
}
else
{
# If path is UNC or local
$ExternalBins = ('{0}\bins' -f $ModsPath)
if (Test-Path -Path $ExternalBins"\*.exe")
{
$ExternalBinsNames = (Get-ChildItem -Path $ExternalBins -Name -Recurse -Include *.exe)
# Delete Local Bins that don't exist Externally
foreach ($Bin in $InternalBinsNames)
{
if ($Bin -notin $ExternalBinsNames)
{
$null = (Remove-Item -Path $LocalMods\bins\$Bin -Force -Confirm:$False -ErrorAction SilentlyContinue)
}
}
# Copy newer external bins
foreach ($Bin in $ExternalBinsNames)
{
$dateExternalBin = ''
$dateLocalBin = ''
if (Test-Path -Path $LocalMods"\bins\"$Bin)
{
$dateLocalBin = (Get-Item -Path ('{0}\bins\{1}' -f $LocalMods, $Bin)).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
}
$dateExternalBin = (Get-Item -Path ('{0}\{1}' -f $ExternalBins, $Bin)).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
if ($dateExternalBin -gt $dateLocalBin)
{
$null = Copy-Item -Path $ExternalBins\$Bin -Destination $LocalMods\bins\$Bin -Force -ErrorAction SilentlyContinue
}
}
}
if ((Test-Path -Path $ExternalMods"\*.ps1") -or (Test-Path -Path $ExternalMods"\*.txt"))
{
# Get File Names Externally
$ExternalModsNames = Get-ChildItem -Path $ExternalMods -Name -Recurse -Include *.ps1, *.txt
# Delete Local Mods that don't exist Externally
$DeletedMods = 0
foreach ($Mod in $InternalModsNames)
{
if ($Mod -notin $ExternalModsNames)
{
$null = Remove-Item -Path $LocalMods\$Mod -Force -ErrorAction SilentlyContinue
$DeletedMods++
}
}
# Copy newer external mods
foreach ($Mod in $ExternalModsNames)
{
$dateExternalMod = ''
$dateLocalMod = ''
if (Test-Path -Path $LocalMods"\"$Mod)
{
$dateLocalMod = (Get-Item -Path ('{0}\{1}' -f $LocalMods, $Mod)).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
}
$dateExternalMod = (Get-Item -Path ('{0}\{1}' -f $ExternalMods, $Mod)).LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
if ($dateExternalMod -gt $dateLocalMod)
{
$null = Copy-Item -Path $ExternalMods\$Mod -Destination $LocalMods\$Mod -Force -ErrorAction SilentlyContinue
$ModsUpdated++
}
}
}
else
{
$Script:ReachNoPath = $True
}
return $ModsUpdated, $DeletedMods
}
} }

View File

@ -1,82 +1,77 @@
#Function to check the connectivity # Function to check the connectivity
function Test-Network { function Test-Network
{
#Init
#Init $timeout = 0
$timeout = 0
#Test connectivity during 30 min then timeout # Test connectivity during 30 min then timeout
Write-ToLog "Checking internet connection..." "Yellow" Write-ToLog -LogMsg 'Checking internet connection...' -LogColor 'Yellow'
While ($timeout -lt 1800) { while ($timeout -lt 1800)
{
$URLtoTest = 'https://raw.githubusercontent.com/Romanitho/Winget-AutoUpdate/main/LICENSE'
$URLcontent = ((Invoke-WebRequest -Uri $URLtoTest -UseBasicParsing).content)
$URLtoTest = "https://raw.githubusercontent.com/Romanitho/Winget-AutoUpdate/main/LICENSE" if ($URLcontent -like '*MIT License*')
$URLcontent = ((Invoke-WebRequest -URI $URLtoTest -UseBasicParsing).content) {
Write-ToLog -LogMsg 'Connected !' -LogColor 'Green'
if ($URLcontent -like "*MIT License*") { # Check for metered connection
$null = (Add-Type -AssemblyName Windows.Networking)
$null = [Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType = WindowsRuntime]
$cost = [Windows.Networking.Connectivity.NetworkInformation]::GetInternetConnectionProfile().GetConnectionCost()
Write-ToLog "Connected !" "Green" if ($cost.ApproachingDataLimit -or $cost.OverDataLimit -or $cost.Roaming -or $cost.BackgroundDataUsageRestricted -or ($cost.NetworkCostType -ne 'Unrestricted'))
{
#Check for metered connection Write-ToLog -LogMsg 'Metered connection detected.' -LogColor 'Yellow'
[void][Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType = WindowsRuntime]
$cost = [Windows.Networking.Connectivity.NetworkInformation]::GetInternetConnectionProfile().GetConnectionCost()
if ($cost.ApproachingDataLimit -or $cost.OverDataLimit -or $cost.Roaming -or $cost.BackgroundDataUsageRestricted -or ($cost.NetworkCostType -ne "Unrestricted")) {
Write-ToLog "Metered connection detected." "Yellow"
if ($WAUConfig.WAU_DoNotRunOnMetered -eq 1) {
Write-ToLog "WAU is configured to bypass update checking on metered connection"
return $false
}
else {
Write-ToLog "WAU is configured to force update checking on metered connection"
return $true
}
if ($WAUConfig.WAU_DoNotRunOnMetered -eq 1)
{
Write-ToLog -LogMsg 'WAU is configured to bypass update checking on metered connection'
return $false
} }
else { else
{
return $true Write-ToLog -LogMsg 'WAU is configured to force update checking on metered connection'
return $true
} }
}
else
{
return $true
}
}
else
{
Start-Sleep -Seconds 10
$timeout += 10
} # Send Warning Notif if no connection for 5 min
else { if ($timeout -eq 300)
{
# Log
Write-ToLog -LogMsg "Notify 'No connection' sent." -LogColor 'Yellow'
Start-Sleep 10 # Notif
$timeout += 10 $Title = $NotifLocale.local.outputs.output[0].title
$Message = $NotifLocale.local.outputs.output[0].message
$MessageType = 'warning'
$Balise = 'Connection'
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise
}
}
}
#Send Warning Notif if no connection for 5 min # Send Timeout Notif if no connection for 30 min
if ($timeout -eq 300) { Write-ToLog -LogMsg 'Timeout. No internet connection !' -LogColor 'Red'
#Log
Write-ToLog "Notify 'No connection' sent." "Yellow"
#Notif # Notif
$Title = $NotifLocale.local.outputs.output[0].title $Title = $NotifLocale.local.outputs.output[1].title
$Message = $NotifLocale.local.outputs.output[0].message $Message = $NotifLocale.local.outputs.output[1].message
$MessageType = "warning" $MessageType = 'error'
$Balise = "Connection" $Balise = 'Connection'
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise
}
}
}
#Send Timeout Notif if no connection for 30 min
Write-ToLog "Timeout. No internet connection !" "Red"
#Notif
$Title = $NotifLocale.local.outputs.output[1].title
$Message = $NotifLocale.local.outputs.output[1].message
$MessageType = "error"
$Balise = "Connection"
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise
return $false
return $false
} }

View File

@ -1,25 +1,34 @@
#Function to check if there is a Pending Reboot # Function to check if there is a Pending Reboot
function Test-PendingReboot { function Test-PendingReboot
{
$Computer = $env:COMPUTERNAME
$PendingReboot = $false
$Computer = $env:COMPUTERNAME $HKLM = [UInt32] '0x80000002'
$PendingReboot = $false $WMI_Reg = [WMIClass] ('\\{0}\root\default:StdRegProv' -f $Computer)
$HKLM = [UInt32] "0x80000002" if ($WMI_Reg)
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv" {
if (($WMI_Reg.EnumKey($HKLM, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\')).sNames -contains 'RebootPending')
{
$PendingReboot = $true
}
if (($WMI_Reg.EnumKey($HKLM, 'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\')).sNames -contains 'RebootRequired')
{
$PendingReboot = $true
}
if ($WMI_Reg) { # Checking for SCCM namespace
if (($WMI_Reg.EnumKey($HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")).sNames -contains 'RebootPending') { $PendingReboot = $true } $SCCM_Namespace = Get-WmiObject -Namespace ROOT\CCM\ClientSDK -List -ComputerName $Computer -ErrorAction Ignore
if (($WMI_Reg.EnumKey($HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")).sNames -contains 'RebootRequired') { $PendingReboot = $true } if ($SCCM_Namespace)
{
#Checking for SCCM namespace if (([WmiClass]('\\{0}\ROOT\CCM\ClientSDK:CCM_ClientUtilities' -f $Computer)).DetermineIfRebootPending().RebootPending -eq $true)
$SCCM_Namespace = Get-WmiObject -Namespace ROOT\CCM\ClientSDK -List -ComputerName $Computer -ErrorAction Ignore {
if ($SCCM_Namespace) { $PendingReboot = $true
if (([WmiClass]"\\$Computer\ROOT\CCM\ClientSDK:CCM_ClientUtilities").DetermineIfRebootPending().RebootPending -eq $true) { $PendingReboot = $true } }
} }
}
}
return $PendingReboot
return $PendingReboot
} }

View File

@ -1,123 +1,137 @@
#Function to update an App # Function to update an App
Function Update-App ($app) { function Update-App
{
# Get App Info
[CmdletBinding()]
param
(
$app
)
$ReleaseNoteURL = Get-AppInfo $app.Id
if ($ReleaseNoteURL)
{
$Button1Text = $NotifLocale.local.outputs.output[10].message
}
#Get App Info # Send available update notification
$ReleaseNoteURL = Get-AppInfo $app.Id Write-ToLog -LogMsg ('Updating {0} from {1} to {2}...' -f $app.Name, $app.Version, $app.AvailableVersion) -LogColor 'Cyan'
if ($ReleaseNoteURL) { $Title = $NotifLocale.local.outputs.output[2].title -f $($app.Name)
$Button1Text = $NotifLocale.local.outputs.output[10].message $Message = $NotifLocale.local.outputs.output[2].message -f $($app.Version), $($app.AvailableVersion)
} $MessageType = 'info'
$Balise = $($app.Name)
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise -Button1Action $ReleaseNoteURL -Button1Text $Button1Text
#Send available update notification # Check if mods exist for preinstall/install/upgrade
Write-ToLog "Updating $($app.Name) from $($app.Version) to $($app.AvailableVersion)..." "Cyan" $ModsPreInstall, $ModsOverride, $ModsUpgrade, $ModsInstall, $ModsInstalled = Test-Mods $($app.Id)
$Title = $NotifLocale.local.outputs.output[2].title -f $($app.Name)
$Message = $NotifLocale.local.outputs.output[2].message -f $($app.Version), $($app.AvailableVersion)
$MessageType = "info"
$Balise = $($app.Name)
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise -Button1Action $ReleaseNoteURL -Button1Text $Button1Text
#Check if mods exist for preinstall/install/upgrade # Winget upgrade
$ModsPreInstall, $ModsOverride, $ModsUpgrade, $ModsInstall, $ModsInstalled = Test-Mods $($app.Id) Write-ToLog -LogMsg ("########## WINGET UPGRADE PROCESS STARTS FOR APPLICATION ID '{0}' ##########" -f $app.Id) -LogColor 'Gray'
#Winget upgrade # If PreInstall script exist
Write-ToLog "########## WINGET UPGRADE PROCESS STARTS FOR APPLICATION ID '$($App.Id)' ##########" "Gray" if ($ModsPreInstall)
{
Write-ToLog -LogMsg ('Modifications for {0} before upgrade are being applied...' -f $app.Id) -LogColor 'Yellow'
& "$ModsPreInstall"
}
#If PreInstall script exist # Run Winget Upgrade command
if ($ModsPreInstall) { if ($ModsOverride)
Write-ToLog "Modifications for $($app.Id) before upgrade are being applied..." "Yellow" {
& "$ModsPreInstall" Write-ToLog -LogMsg ('-> Running (overriding default): Winget upgrade --id {0} --accept-package-agreements --accept-source-agreements --override {1}' -f $app.Id, $ModsOverride)
} & $Winget upgrade --id $($app.Id) --accept-package-agreements --accept-source-agreements --override $ModsOverride | Tee-Object -FilePath $LogFile -Append
}
else
{
Write-ToLog -LogMsg ('-> Running: Winget upgrade --id {0} --accept-package-agreements --accept-source-agreements -h' -f $app.Id)
& $Winget upgrade --id $($app.Id) --accept-package-agreements --accept-source-agreements -h | Tee-Object -FilePath $LogFile -Append
}
#Run Winget Upgrade command if ($ModsUpgrade)
if ($ModsOverride) { {
Write-ToLog "-> Running (overriding default): Winget upgrade --id $($app.Id) --accept-package-agreements --accept-source-agreements --override $ModsOverride" Write-ToLog -LogMsg ('Modifications for {0} during upgrade are being applied...' -f $app.Id) -LogColor 'Yellow'
& $Winget upgrade --id $($app.Id) --accept-package-agreements --accept-source-agreements --override $ModsOverride | Tee-Object -file $LogFile -Append & "$ModsUpgrade"
} }
else {
Write-ToLog "-> Running: Winget upgrade --id $($app.Id) --accept-package-agreements --accept-source-agreements -h"
& $Winget upgrade --id $($app.Id) --accept-package-agreements --accept-source-agreements -h | Tee-Object -file $LogFile -Append
}
if ($ModsUpgrade) { # Check if application updated properly
Write-ToLog "Modifications for $($app.Id) during upgrade are being applied..." "Yellow" $FailedToUpgrade = $false
& "$ModsUpgrade" $ConfirmInstall = Confirm-Installation $($app.Id) $($app.AvailableVersion)
}
#Check if application updated properly if ($ConfirmInstall -ne $true)
$FailedToUpgrade = $false {
$ConfirmInstall = Confirm-Installation $($app.Id) $($app.AvailableVersion) # Upgrade failed!
# Test for a Pending Reboot (Component Based Servicing/WindowsUpdate/CCM_ClientUtilities)
$PendingReboot = Test-PendingReboot
if ($PendingReboot -eq $true)
{
Write-ToLog -LogMsg ("-> A Pending Reboot lingers and probably prohibited {0} from upgrading...`n-> ...an install for {1} is NOT executed!" -f $app.Name) -LogColor 'Red'
$FailedToUpgrade = $true
break
}
if ($ConfirmInstall -ne $true) { # If app failed to upgrade, run Install command
#Upgrade failed! Write-ToLog -LogMsg ('-> An upgrade for {0} failed, now trying an install instead...' -f $app.Name) -LogColor 'Yellow'
#Test for a Pending Reboot (Component Based Servicing/WindowsUpdate/CCM_ClientUtilities)
$PendingReboot = Test-PendingReboot
if ($PendingReboot -eq $true) {
Write-ToLog "-> A Pending Reboot lingers and probably prohibited $($app.Name) from upgrading...`n-> ...an install for $($app.Name) is NOT executed!" "Red"
$FailedToUpgrade = $true
break
}
#If app failed to upgrade, run Install command if ($ModsOverride)
Write-ToLog "-> An upgrade for $($app.Name) failed, now trying an install instead..." "Yellow" {
Write-ToLog -LogMsg ('-> Running (overriding default): Winget install --id {0} --accept-package-agreements --accept-source-agreements --force --override {1}' -f $app.Id, $ModsOverride)
& $Winget install --id $($app.Id) --accept-package-agreements --accept-source-agreements --force --override $ModsOverride | Tee-Object -FilePath $LogFile -Append
}
else
{
Write-ToLog -LogMsg ('-> Running: Winget install --id {0} --accept-package-agreements --accept-source-agreements --force -h' -f $app.Id)
& $Winget install --id $($app.Id) --accept-package-agreements --accept-source-agreements --force -h | Tee-Object -FilePath $LogFile -Append
}
if ($ModsOverride) { if ($ModsInstall)
Write-ToLog "-> Running (overriding default): Winget install --id $($app.Id) --accept-package-agreements --accept-source-agreements --force --override $ModsOverride" {
& $Winget install --id $($app.Id) --accept-package-agreements --accept-source-agreements --force --override $ModsOverride | Tee-Object -file $LogFile -Append Write-ToLog -LogMsg ('Modifications for {0} during install are being applied...' -f $app.Id) -LogColor 'Yellow'
} & "$ModsInstall"
else { }
Write-ToLog "-> Running: Winget install --id $($app.Id) --accept-package-agreements --accept-source-agreements --force -h"
& $Winget install --id $($app.Id) --accept-package-agreements --accept-source-agreements --force -h | Tee-Object -file $LogFile -Append
}
if ($ModsInstall) { # Check if application installed properly
Write-ToLog "Modifications for $($app.Id) during install are being applied..." "Yellow" $ConfirmInstall = Confirm-Installation $($app.Id) $($app.AvailableVersion)
& "$ModsInstall" if ($ConfirmInstall -eq $false)
} {
$FailedToUpgrade = $true
}
}
#Check if application installed properly if ($FailedToUpgrade -eq $false)
$ConfirmInstall = Confirm-Installation $($app.Id) $($app.AvailableVersion) {
if ($ConfirmInstall -eq $false) { if ($ModsInstalled)
$FailedToUpgrade = $true {
} Write-ToLog -LogMsg ('Modifications for {0} after upgrade/install are being applied...' -f $app.Id) -LogColor 'Yellow'
} & "$ModsInstalled"
}
}
if ($FailedToUpgrade -eq $false) { Write-ToLog -LogMsg ("########## WINGET UPGRADE PROCESS FINISHED FOR APPLICATION ID '{0}' ##########" -f $app.Id) -LogColor 'Gray'
if ($ModsInstalled) {
Write-ToLog "Modifications for $($app.Id) after upgrade/install are being applied..." "Yellow"
& "$ModsInstalled"
}
}
Write-ToLog "########## WINGET UPGRADE PROCESS FINISHED FOR APPLICATION ID '$($App.Id)' ##########" "Gray" # Notify installation
if ($FailedToUpgrade -eq $false)
{
# Send success updated app notification
Write-ToLog -LogMsg ('{0} updated to {1} !' -f $app.Name, $app.AvailableVersion) -LogColor 'Green'
#Notify installation # Send Notif
if ($FailedToUpgrade -eq $false) { $Title = $NotifLocale.local.outputs.output[3].title -f $($app.Name)
$Message = $NotifLocale.local.outputs.output[3].message -f $($app.AvailableVersion)
#Send success updated app notification $MessageType = 'success'
Write-ToLog "$($app.Name) updated to $($app.AvailableVersion) !" "Green" $Balise = $($app.Name)
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise -Button1Action $ReleaseNoteURL -Button1Text $Button1Text
#Send Notif $Script:InstallOK += 1
$Title = $NotifLocale.local.outputs.output[3].title -f $($app.Name) }
$Message = $NotifLocale.local.outputs.output[3].message -f $($app.AvailableVersion) else
$MessageType = "success" {
$Balise = $($app.Name) # Send failed updated app notification
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise -Button1Action $ReleaseNoteURL -Button1Text $Button1Text Write-ToLog -LogMsg ('{0} update failed.' -f $app.Name) -LogColor 'Red'
$Script:InstallOK += 1
}
else {
#Send failed updated app notification
Write-ToLog "$($app.Name) update failed." "Red"
#Send Notif
$Title = $NotifLocale.local.outputs.output[4].title -f $($app.Name)
$Message = $NotifLocale.local.outputs.output[4].message
$MessageType = "error"
$Balise = $($app.Name)
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise -Button1Action $ReleaseNoteURL -Button1Text $Button1Text
}
# Send Notif
$Title = $NotifLocale.local.outputs.output[4].title -f $($app.Name)
$Message = $NotifLocale.local.outputs.output[4].message
$MessageType = 'error'
$Balise = $($app.Name)
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Balise $Balise -Button1Action $ReleaseNoteURL -Button1Text $Button1Text
}
} }

View File

@ -1,77 +1,74 @@
#Function to update WAU # Function to update WAU
function Update-WAU { function Update-WAU
{
$OnClickAction = 'https://github.com/Romanitho/Winget-AutoUpdate/releases'
$Button1Text = $NotifLocale.local.outputs.output[10].message
$OnClickAction = "https://github.com/Romanitho/Winget-AutoUpdate/releases" #Send available update notification
$Button1Text = $NotifLocale.local.outputs.output[10].message $Title = $NotifLocale.local.outputs.output[2].title -f 'Winget-AutoUpdate'
$Message = $NotifLocale.local.outputs.output[2].message -f $WAUCurrentVersion, $WAUAvailableVersion
$MessageType = 'info'
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Button1Action $OnClickAction -Button1Text $Button1Text
#Send available update notification # Run WAU update
$Title = $NotifLocale.local.outputs.output[2].title -f "Winget-AutoUpdate" try
$Message = $NotifLocale.local.outputs.output[2].message -f $WAUCurrentVersion, $WAUAvailableVersion {
$MessageType = "info" # Force to create a zip file
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Button1Action $OnClickAction -Button1Text $Button1Text $ZipFile = ('{0}\WAU_update.zip' -f $WorkingDir)
$null = New-Item -Path $ZipFile -ItemType File -Force
#Run WAU update # Download the zip
try { Write-ToLog -LogMsg ('Downloading the GitHub Repository version {0}' -f $WAUAvailableVersion) -LogColor 'Cyan'
$null = (Invoke-RestMethod -Uri ('https://github.com/Romanitho/Winget-AutoUpdate/releases/download/v{0}/WAU.zip' -f ($WAUAvailableVersion)) -OutFile $ZipFile)
#Force to create a zip file # Extract Zip File
$ZipFile = "$WorkingDir\WAU_update.zip" Write-ToLog -LogMsg 'Unzipping the WAU Update package' -LogColor 'Cyan'
New-Item $ZipFile -ItemType File -Force | Out-Null $location = ('{0}\WAU_update' -f $WorkingDir)
$null = (Expand-Archive -Path $ZipFile -DestinationPath $location -Force)
$null = (Get-ChildItem -Path $location -Recurse | Unblock-File -ErrorAction SilentlyContinue)
#Download the zip # Update scritps
Write-ToLog "Downloading the GitHub Repository version $WAUAvailableVersion" "Cyan" Write-ToLog -LogMsg 'Updating WAU...' -LogColor 'Yellow'
Invoke-RestMethod -Uri "https://github.com/Romanitho/Winget-AutoUpdate/releases/download/v$($WAUAvailableVersion)/WAU.zip" -OutFile $ZipFile $TempPath = (Resolve-Path -Path ('{0}\Winget-AutoUpdate\' -f $location) -ErrorAction SilentlyContinue)[0].Path
if ($TempPath)
{
$null = (Copy-Item -Path ('{0}\*' -f $TempPath) -Destination ('{0}\' -f $WorkingDir) -Exclude 'icons' -Recurse -Force -Confirm:$false)
}
#Extract Zip File # Remove update zip file and update temp folder
Write-ToLog "Unzipping the WAU Update package" "Cyan" Write-ToLog -LogMsg 'Done. Cleaning temp files...' -LogColor 'Cyan'
$location = "$WorkingDir\WAU_update" $null = (Remove-Item -Path $ZipFile -Force -Confirm:$false -ErrorAction SilentlyContinue)
Expand-Archive -Path $ZipFile -DestinationPath $location -Force $null = (Remove-Item -Path $location -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue)
Get-ChildItem -Path $location -Recurse | Unblock-File
#Update scritps # Set new version to registry
Write-ToLog "Updating WAU..." "Yellow" $WAUConfig | New-ItemProperty -Name DisplayVersion -Value $WAUAvailableVersion -Force
$TempPath = (Resolve-Path "$location\Winget-AutoUpdate\")[0].Path $WAUConfig | New-ItemProperty -Name VersionMajor -Value ([version]$WAUAvailableVersion.Replace('-', '.')).Major -Force
if ($TempPath) { $WAUConfig | New-ItemProperty -Name VersionMinor -Value ([version]$WAUAvailableVersion.Replace('-', '.')).Minor -Force
Copy-Item -Path "$TempPath\*" -Destination "$WorkingDir\" -Exclude "icons" -Recurse -Force
}
#Remove update zip file and update temp folder # Set Post Update actions to 1
Write-ToLog "Done. Cleaning temp files..." "Cyan" $WAUConfig | New-ItemProperty -Name WAU_PostUpdateActions -Value 1 -Force
Remove-Item -Path $ZipFile -Force -ErrorAction SilentlyContinue
Remove-Item -Path $location -Recurse -Force -ErrorAction SilentlyContinue
#Set new version to registry # Send success Notif
$WAUConfig | New-ItemProperty -Name DisplayVersion -Value $WAUAvailableVersion -Force Write-ToLog -LogMsg 'WAU Update completed.' -LogColor 'Green'
$WAUConfig | New-ItemProperty -Name VersionMajor -Value ([version]$WAUAvailableVersion.Replace("-", ".")).Major -Force $Title = $NotifLocale.local.outputs.output[3].title -f 'Winget-AutoUpdate'
$WAUConfig | New-ItemProperty -Name VersionMinor -Value ([version]$WAUAvailableVersion.Replace("-", ".")).Minor -Force $Message = $NotifLocale.local.outputs.output[3].message -f $WAUAvailableVersion
$MessageType = 'success'
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Button1Action $OnClickAction -Button1Text $Button1Text
#Set Post Update actions to 1 # Rerun with newer version
$WAUConfig | New-ItemProperty -Name WAU_PostUpdateActions -Value 1 -Force Write-ToLog -LogMsg 'Re-run WAU'
Start-Process -FilePath powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"$WorkingDir\winget-upgrade.ps1`""
#Send success Notif
Write-ToLog "WAU Update completed." "Green"
$Title = $NotifLocale.local.outputs.output[3].title -f "Winget-AutoUpdate"
$Message = $NotifLocale.local.outputs.output[3].message -f $WAUAvailableVersion
$MessageType = "success"
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Button1Action $OnClickAction -Button1Text $Button1Text
#Rerun with newer version
Write-ToLog "Re-run WAU"
Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"$WorkingDir\winget-upgrade.ps1`""
exit
}
catch {
#Send Error Notif
$Title = $NotifLocale.local.outputs.output[4].title -f "Winget-AutoUpdate"
$Message = $NotifLocale.local.outputs.output[4].message
$MessageType = "error"
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Button1Action $OnClickAction -Button1Text $Button1Text
Write-ToLog "WAU Update failed" "Red"
}
exit
}
catch
{
# Send Error Notif
$Title = $NotifLocale.local.outputs.output[4].title -f 'Winget-AutoUpdate'
$Message = $NotifLocale.local.outputs.output[4].message
$MessageType = 'error'
Start-NotifTask -Title $Title -Message $Message -MessageType $MessageType -Button1Action $OnClickAction -Button1Text $Button1Text
Write-ToLog -LogMsg 'WAU Update failed' -LogColor 'Red'
}
} }

View File

@ -1,14 +1,22 @@
#Write to Log Function # Write to Log Function
function Write-ToLog ($LogMsg, $LogColor = "White") { function Write-ToLog
{
# Get log
[CmdletBinding()]
param
(
[string]
$LogMsg,
[string]
$LogColor = 'White'
)
#Get log $Log = ('{0} - {1}' -f (Get-Date -UFormat '%T'), $LogMsg)
$Log = "$(Get-Date -UFormat "%T") - $LogMsg"
#Echo log #Echo log
$Log | Write-host -ForegroundColor $LogColor $Log | Write-Host -ForegroundColor $LogColor
#Write log to file
$Log | Out-File -FilePath $LogFile -Append
#Write log to file
$Log | Out-File -FilePath $LogFile -Append -Force -Confirm:$false
} }