Merge pull request #408 from Romanitho/revert

Revert "Merge pull request #399 from jhochwald/main"
pull/413/head
Romain 2023-10-03 11:34:40 +02:00 committed by GitHub
commit a78fb612f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 2652 additions and 3349 deletions

View File

@ -92,243 +92,187 @@
[CmdletBinding()] [CmdletBinding()]
param( param(
[Alias('S')] [Parameter(Mandatory = $False)] [Alias('S')] [Switch] $Silent = $false,
[Switch] [Parameter(Mandatory = $False)] [Alias('Path')] [String] $WingetUpdatePath = "$env:ProgramData\Winget-AutoUpdate",
$Silent = $false, [Parameter(Mandatory = $False)] [Alias('List')] [String] $ListPath,
[Alias('Path')] [Parameter(Mandatory = $False)] [Alias('Mods')] [String] $ModsPath,
[String] [Parameter(Mandatory = $False)] [Alias('AzureBlobURL')] [String] $AzureBlobSASURL,
$WingetUpdatePath = "$env:ProgramData\Winget-AutoUpdate", [Parameter(Mandatory = $False)] [Switch] $DoNotUpdate = $false,
[Alias('List')] [Parameter(Mandatory = $False)] [Switch] $DisableWAUAutoUpdate = $false,
[String] [Parameter(Mandatory = $False)] [Switch] $RunOnMetered = $false,
$ListPath, [Parameter(Mandatory = $False)] [Switch] $Uninstall = $false,
[Alias('Mods')] [Parameter(Mandatory = $False)] [Switch] $NoClean = $false,
[String] [Parameter(Mandatory = $False)] [Switch] $DesktopShortcut = $false,
$ModsPath, [Parameter(Mandatory = $False)] [Switch] $StartMenuShortcut = $false,
[Alias('AzureBlobURL')] [Parameter(Mandatory = $False)] [Switch] $UseWhiteList = $false,
[String] [Parameter(Mandatory = $False)] [ValidateSet("Full", "SuccessOnly", "None")] [String] $NotificationLevel = "Full",
$AzureBlobSASURL, [Parameter(Mandatory = $False)] [Switch] $UpdatesAtLogon = $false,
[Switch] [Parameter(Mandatory = $False)] [ValidateSet("Daily", "BiDaily", "Weekly", "BiWeekly", "Monthly", "Never")] [String] $UpdatesInterval = "Daily",
$DoNotUpdate = $false, [Parameter(Mandatory = $False)] [DateTime] $UpdatesAtTime = ("06am"),
[Switch] [Parameter(Mandatory = $False)] [Switch] $BypassListForUsers = $false,
$DisableWAUAutoUpdate = $false, [Parameter(Mandatory = $False)] [Switch] $InstallUserContext = $false,
[Switch] [Parameter(Mandatory = $False)] [ValidateRange(0, 99)] [int32] $MaxLogFiles = 3,
$RunOnMetered = $false, [Parameter(Mandatory = $False)] [int64] $MaxLogSize = 1048576 # in bytes, default is 1048576 = 1 MB
[Switch]
$Uninstall = $false,
[Switch]
$NoClean = $false,
[Switch]
$DesktopShortcut = $false,
[Switch]
$StartMenuShortcut = $false,
[Switch]
$UseWhiteList = $false,
[ValidateSet('Full', 'SuccessOnly', 'None')]
[String]
$NotificationLevel = 'Full',
[Switch]
$UpdatesAtLogon = $false,
[ValidateSet('Daily', 'BiDaily', 'Weekly', 'BiWeekly', 'Monthly', 'Never')]
[String]
$UpdatesInterval = 'Daily',
[DateTime]
$UpdatesAtTime = ('06am'),
[Switch]
$BypassListForUsers = $false,
[Switch]
$InstallUserContext = $false,
[ValidateRange(0, 99)]
[int]
$MaxLogFiles = 3,
[long]
$MaxLogSize = 1048576 # in bytes, default is 1048576 = 1 MB
) )
<# FUNCTIONS #> <# FUNCTIONS #>
function Install-Prerequisites function Install-Prerequisites {
{
Write-Host -Object "`nChecking prerequisites..." -ForegroundColor Yellow Write-Host "`nChecking prerequisites..." -ForegroundColor 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 -FilterScript { $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 }
$_.GetValue('DisplayName') -like $Visual2019 -or $_.GetValue('DisplayName') -like $Visual2022
}
#If not installed, ask for installation #If not installed, ask for installation
if (!($path)) if (!($path)) {
{
#If -silent option, force installation #If -silent option, force installation
if ($Silent) if ($Silent) {
{
$InstallApp = 1 $InstallApp = 1
} }
else else {
{
#Ask for installation #Ask for installation
$MsgBoxTitle = 'Winget Prerequisites' $MsgBoxTitle = "Winget Prerequisites"
$MsgBoxContent = 'Microsoft Visual C++ 2015-2022 is required. Would you like to install it?' $MsgBoxContent = "Microsoft Visual C++ 2015-2022 is required. Would you like to install it?"
$MsgBoxTimeOut = 60 $MsgBoxTimeOut = 60
$MsgBoxReturn = (New-Object -ComObject 'Wscript.Shell').Popup($MsgBoxContent, $MsgBoxTimeOut, $MsgBoxTitle, 4 + 32) $MsgBoxReturn = (New-Object -ComObject "Wscript.Shell").Popup($MsgBoxContent, $MsgBoxTimeOut, $MsgBoxTitle, 4 + 32)
if ($MsgBoxReturn -ne 7) if ($MsgBoxReturn -ne 7) {
{
$InstallApp = 1 $InstallApp = 1
} }
else else {
{
$InstallApp = 0 $InstallApp = 0
} }
} }
#Install if approved #Install if approved
if ($InstallApp -eq 1) if ($InstallApp -eq 1) {
{ try {
try if ((Get-CimInStance Win32_OperatingSystem).OSArchitecture -like "*64*") {
{ $OSArch = "x64"
if ((Get-CimInstance Win32_OperatingSystem).OSArchitecture -like '*64*')
{
$OSArch = 'x64'
} }
else else {
{ $OSArch = "x86"
$OSArch = 'x86'
} }
Write-Host -Object "-> Downloading VC_redist.$OSArch.exe..." Write-host "-> Downloading VC_redist.$OSArch.exe..."
$SourceURL = "https://aka.ms/vs/17/release/VC_redist.$OSArch.exe" $SourceURL = "https://aka.ms/vs/17/release/VC_redist.$OSArch.exe"
$Installer = $WingetUpdatePath + "\VC_redist.$OSArch.exe" $Installer = $WingetUpdatePath + "\VC_redist.$OSArch.exe"
$ProgressPreference = 'SilentlyContinue' $ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $SourceURL -UseBasicParsing -OutFile (New-Item -Path $Installer -Force) Invoke-WebRequest $SourceURL -UseBasicParsing -OutFile (New-Item -Path $Installer -Force)
Write-Host -Object "-> Installing VC_redist.$OSArch.exe..." Write-host "-> Installing VC_redist.$OSArch.exe..."
Start-Process -FilePath $Installer -ArgumentList '/quiet /norestart' -Wait Start-Process -FilePath $Installer -Args "/quiet /norestart" -Wait
Remove-Item $Installer -ErrorAction Ignore Remove-Item $Installer -ErrorAction Ignore
Write-Host -Object 'MS Visual C++ 2015-2022 installed successfully' -ForegroundColor Green Write-host "MS Visual C++ 2015-2022 installed successfully" -ForegroundColor Green
} }
catch catch {
{ Write-host "MS Visual C++ 2015-2022 installation failed." -ForegroundColor Red
Write-Host -Object 'MS Visual C++ 2015-2022 installation failed.' -ForegroundColor Red Start-Sleep 3
Start-Sleep -Seconds 3
} }
} }
else else {
{ Write-host "-> MS Visual C++ 2015-2022 will not be installed." -ForegroundColor Magenta
Write-Host -Object '-> MS Visual C++ 2015-2022 will not be installed.' -ForegroundColor Magenta
} }
} }
else else {
{ Write-Host "Prerequisites checked. OK" -ForegroundColor Green
Write-Host -Object 'Prerequisites checked. OK' -ForegroundColor Green
} }
} }
function Install-WinGet function Install-WinGet {
{
Write-Host -Object "`nChecking if Winget is installed" -ForegroundColor Yellow Write-Host "`nChecking if Winget is installed" -ForegroundColor Yellow
#Check Package Install #Check Package Install
$TestWinGet = Get-AppxProvisionedPackage -Online | Where-Object -FilterScript { $TestWinGet = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq "Microsoft.DesktopAppInstaller" }
$_.DisplayName -eq 'Microsoft.DesktopAppInstaller'
}
#Current: v1.5.2201 = 1.20.2201.0 = 2023.808.2243.0 #Current: v1.5.2201 = 1.20.2201.0 = 2023.808.2243.0
if ([Version]$TestWinGet.Version -ge '2023.808.2243.0') If ([Version]$TestWinGet.Version -ge "2023.808.2243.0") {
{
Write-Host -Object 'Winget is Installed' -ForegroundColor Green Write-Host "Winget is Installed" -ForegroundColor Green
} }
else Else {
{
Write-Host -Object '-> Winget is not installed:' Write-Host "-> Winget is not installed:"
#Check if $WingetUpdatePath exist #Check if $WingetUpdatePath exist
if (!(Test-Path $WingetUpdatePath)) if (!(Test-Path $WingetUpdatePath)) {
{ New-Item -ItemType Directory -Force -Path $WingetUpdatePath | Out-Null
$null = New-Item -ItemType Directory -Force -Path $WingetUpdatePath
} }
#Downloading and Installing Dependencies in SYSTEM context #Downloading and Installing Dependencies in SYSTEM context
if (!(Get-AppxPackage -Name 'Microsoft.UI.Xaml.2.7')) if (!(Get-AppxPackage -Name 'Microsoft.UI.Xaml.2.7')) {
{ Write-Host "-> Downloading Microsoft.UI.Xaml.2.7..."
Write-Host -Object '-> Downloading Microsoft.UI.Xaml.2.7...' $UiXamlUrl = "https://www.nuget.org/api/v2/package/Microsoft.UI.Xaml/2.7.0"
$UiXamlUrl = 'https://www.nuget.org/api/v2/package/Microsoft.UI.Xaml/2.7.0'
$UiXamlZip = "$WingetUpdatePath\Microsoft.UI.XAML.2.7.zip" $UiXamlZip = "$WingetUpdatePath\Microsoft.UI.XAML.2.7.zip"
Invoke-RestMethod -Uri $UiXamlUrl -OutFile $UiXamlZip Invoke-RestMethod -Uri $UiXamlUrl -OutFile $UiXamlZip
Expand-Archive -Path $UiXamlZip -DestinationPath "$WingetUpdatePath\extracted" -Force Expand-Archive -Path $UiXamlZip -DestinationPath "$WingetUpdatePath\extracted" -Force
try try {
{ Write-Host "-> Installing Microsoft.UI.Xaml.2.7..."
Write-Host -Object '-> Installing Microsoft.UI.Xaml.2.7...' Add-AppxProvisionedPackage -Online -PackagePath "$WingetUpdatePath\extracted\tools\AppX\x64\Release\Microsoft.UI.Xaml.2.7.appx" -SkipLicense | Out-Null
$null = Add-AppxProvisionedPackage -Online -PackagePath "$WingetUpdatePath\extracted\tools\AppX\x64\Release\Microsoft.UI.Xaml.2.7.appx" -SkipLicense Write-host "Microsoft.UI.Xaml.2.7 installed successfully" -ForegroundColor Green
Write-Host -Object 'Microsoft.UI.Xaml.2.7 installed successfully' -ForegroundColor Green
} }
catch catch {
{ Write-Host "Failed to intall Wicrosoft.UI.Xaml.2.7..." -ForegroundColor Red
Write-Host -Object 'Failed to intall Wicrosoft.UI.Xaml.2.7...' -ForegroundColor Red
} }
Remove-Item -Path $UiXamlZip -Force Remove-Item -Path $UiXamlZip -Force
Remove-Item -Path "$WingetUpdatePath\extracted" -Force -Recurse Remove-Item -Path "$WingetUpdatePath\extracted" -Force -Recurse
} }
if (!(Get-AppxPackage -Name 'Microsoft.VCLibs.140.00.UWPDesktop')) if (!(Get-AppxPackage -Name 'Microsoft.VCLibs.140.00.UWPDesktop')) {
{ Write-Host "-> Downloading Microsoft.VCLibs.140.00.UWPDesktop..."
Write-Host -Object '-> Downloading Microsoft.VCLibs.140.00.UWPDesktop...' $VCLibsUrl = "https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx"
$VCLibsUrl = 'https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx'
$VCLibsFile = "$WingetUpdatePath\Microsoft.VCLibs.x64.14.00.Desktop.appx" $VCLibsFile = "$WingetUpdatePath\Microsoft.VCLibs.x64.14.00.Desktop.appx"
Invoke-RestMethod -Uri $VCLibsUrl -OutFile $VCLibsFile Invoke-RestMethod -Uri $VCLibsUrl -OutFile $VCLibsFile
try try {
{ Write-Host "-> Installing Microsoft.VCLibs.140.00.UWPDesktop..."
Write-Host -Object '-> Installing Microsoft.VCLibs.140.00.UWPDesktop...' Add-AppxProvisionedPackage -Online -PackagePath $VCLibsFile -SkipLicense | Out-Null
$null = Add-AppxProvisionedPackage -Online -PackagePath $VCLibsFile -SkipLicense Write-host "Microsoft.VCLibs.140.00.UWPDesktop installed successfully" -ForegroundColor Green
Write-Host -Object 'Microsoft.VCLibs.140.00.UWPDesktop installed successfully' -ForegroundColor Green
} }
catch catch {
{ Write-Host "Failed to intall Microsoft.VCLibs.140.00.UWPDesktop..." -ForegroundColor Red
Write-Host -Object 'Failed to intall Microsoft.VCLibs.140.00.UWPDesktop...' -ForegroundColor Red
} }
Remove-Item -Path $VCLibsFile -Force Remove-Item -Path $VCLibsFile -Force
} }
#Download WinGet MSIXBundle #Download WinGet MSIXBundle
Write-Host -Object '-> Downloading Winget MSIXBundle for App Installer...' Write-Host "-> Downloading Winget MSIXBundle for App Installer..."
$WinGetURL = 'https://github.com/microsoft/winget-cli/releases/download/v1.5.2201/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle' $WinGetURL = "https://github.com/microsoft/winget-cli/releases/download/v1.5.2201/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle"
$WebClient = New-Object -TypeName System.Net.WebClient $WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($WinGetURL, "$WingetUpdatePath\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle") $WebClient.DownloadFile($WinGetURL, "$WingetUpdatePath\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle")
#Install WinGet MSIXBundle in SYSTEM context #Install WinGet MSIXBundle in SYSTEM context
try try {
{ Write-Host "-> Installing Winget MSIXBundle for App Installer..."
Write-Host -Object '-> Installing Winget MSIXBundle for App Installer...' Add-AppxProvisionedPackage -Online -PackagePath "$WingetUpdatePath\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -SkipLicense | Out-Null
$null = Add-AppxProvisionedPackage -Online -PackagePath "$WingetUpdatePath\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -SkipLicense Write-host "Winget MSIXBundle for App Installer installed successfully" -ForegroundColor Green
Write-Host -Object 'Winget MSIXBundle for App Installer installed successfully' -ForegroundColor Green
} }
catch catch {
{ Write-Host "Failed to intall Winget MSIXBundle for App Installer..." -ForegroundColor Red
Write-Host -Object 'Failed to intall Winget MSIXBundle for App Installer...' -ForegroundColor Red
} }
#Remove WinGet MSIXBundle #Remove WinGet MSIXBundle
Remove-Item -Path "$WingetUpdatePath\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -Force -ErrorAction Continue Remove-Item -Path "$WingetUpdatePath\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -Force -ErrorAction Continue
}
} }
function Install-WingetAutoUpdate }
{
Write-Host -Object "`nInstalling WAU..." -ForegroundColor Yellow
try function Install-WingetAutoUpdate {
{
Write-Host "`nInstalling WAU..." -ForegroundColor Yellow
try {
#Copy files to location (and clean old install) #Copy files to location (and clean old install)
if (!(Test-Path $WingetUpdatePath)) if (!(Test-Path $WingetUpdatePath)) {
{ New-Item -ItemType Directory -Force -Path $WingetUpdatePath | Out-Null
$null = New-Item -ItemType Directory -Force -Path $WingetUpdatePath
} }
else else {
{ if (!$NoClean) {
if (!$NoClean)
{
Remove-Item -Path "$WingetUpdatePath\*" -Exclude *.log -Recurse -Force Remove-Item -Path "$WingetUpdatePath\*" -Exclude *.log -Recurse -Force
} }
else else {
{
#Keep critical files #Keep critical files
Get-ChildItem -Path $WingetUpdatePath -Exclude *.txt, mods, logs | Remove-Item -Recurse -Force Get-ChildItem -Path $WingetUpdatePath -Exclude *.txt, mods, logs | Remove-Item -Recurse -Force
} }
@ -336,176 +280,146 @@ function Install-WingetAutoUpdate
Copy-Item -Path "$PSScriptRoot\Winget-AutoUpdate\*" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue Copy-Item -Path "$PSScriptRoot\Winget-AutoUpdate\*" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue
#White List or Black List apps #White List or Black List apps
if ($UseWhiteList) if ($UseWhiteList) {
{ if (!$NoClean) {
if (!$NoClean) if ((Test-Path "$PSScriptRoot\included_apps.txt")) {
{
if ((Test-Path -Path "$PSScriptRoot\included_apps.txt"))
{
Copy-Item -Path "$PSScriptRoot\included_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue Copy-Item -Path "$PSScriptRoot\included_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue
} }
else else {
{ if (!$ListPath) {
if (!$ListPath) New-Item -Path $WingetUpdatePath -Name "included_apps.txt" -ItemType "file" -ErrorAction SilentlyContinue | Out-Null
{
$null = New-Item -Path $WingetUpdatePath -Name 'included_apps.txt' -ItemType 'file' -ErrorAction SilentlyContinue
} }
} }
} }
elseif (!(Test-Path -Path "$WingetUpdatePath\included_apps.txt")) elseif (!(Test-Path "$WingetUpdatePath\included_apps.txt")) {
{ if ((Test-Path "$PSScriptRoot\included_apps.txt")) {
if ((Test-Path -Path "$PSScriptRoot\included_apps.txt"))
{
Copy-Item -Path "$PSScriptRoot\included_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue Copy-Item -Path "$PSScriptRoot\included_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue
} }
else else {
{ if (!$ListPath) {
if (!$ListPath) New-Item -Path $WingetUpdatePath -Name "included_apps.txt" -ItemType "file" -ErrorAction SilentlyContinue | Out-Null
{
$null = New-Item -Path $WingetUpdatePath -Name 'included_apps.txt' -ItemType 'file' -ErrorAction SilentlyContinue
} }
} }
} }
} }
else else {
{ if (!$NoClean) {
if (!$NoClean)
{
Copy-Item -Path "$PSScriptRoot\excluded_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue Copy-Item -Path "$PSScriptRoot\excluded_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue
} }
elseif (!(Test-Path -Path "$WingetUpdatePath\excluded_apps.txt")) elseif (!(Test-Path "$WingetUpdatePath\excluded_apps.txt")) {
{
Copy-Item -Path "$PSScriptRoot\excluded_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue Copy-Item -Path "$PSScriptRoot\excluded_apps.txt" -Destination $WingetUpdatePath -Recurse -Force -ErrorAction SilentlyContinue
} }
} }
# Set dummy regkeys for notification name and icon # Set dummy regkeys for notification name and icon
$null = & "$env:windir\system32\reg.exe" add 'HKCR\AppUserModelId\Windows.SystemToast.Winget.Notification' /v DisplayName /t REG_EXPAND_SZ /d 'Application Update' /f & reg add "HKCR\AppUserModelId\Windows.SystemToast.Winget.Notification" /v DisplayName /t REG_EXPAND_SZ /d "Application Update" /f | Out-Null
$null = & "$env:windir\system32\reg.exe" add 'HKCR\AppUserModelId\Windows.SystemToast.Winget.Notification' /v IconUri /t REG_EXPAND_SZ /d %SystemRoot%\system32\@WindowsUpdateToastIcon.png /f & reg add "HKCR\AppUserModelId\Windows.SystemToast.Winget.Notification" /v IconUri /t REG_EXPAND_SZ /d %SystemRoot%\system32\@WindowsUpdateToastIcon.png /f | Out-Null
# Settings for the scheduled task for Updates # Settings for the scheduled task for Updates
$taskAction = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$($WingetUpdatePath)\winget-upgrade.ps1`"" $taskAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$($WingetUpdatePath)\winget-upgrade.ps1`""
$taskTriggers = @() $taskTriggers = @()
if ($UpdatesAtLogon) if ($UpdatesAtLogon) {
{ $tasktriggers += New-ScheduledTaskTrigger -AtLogOn
$taskTriggers += New-ScheduledTaskTrigger -AtLogOn
} }
if ($UpdatesInterval -eq 'Daily') if ($UpdatesInterval -eq "Daily") {
{ $tasktriggers += New-ScheduledTaskTrigger -Daily -At $UpdatesAtTime
$taskTriggers += New-ScheduledTaskTrigger -Daily -At $UpdatesAtTime
} }
elseif ($UpdatesInterval -eq 'BiDaily') elseif ($UpdatesInterval -eq "BiDaily") {
{ $tasktriggers += New-ScheduledTaskTrigger -Daily -At $UpdatesAtTime -DaysInterval 2
$taskTriggers += New-ScheduledTaskTrigger -Daily -At $UpdatesAtTime -DaysInterval 2
} }
elseif ($UpdatesInterval -eq 'Weekly') elseif ($UpdatesInterval -eq "Weekly") {
{ $tasktriggers += New-ScheduledTaskTrigger -Weekly -At $UpdatesAtTime -DaysOfWeek 2
$taskTriggers += New-ScheduledTaskTrigger -Weekly -At $UpdatesAtTime -DaysOfWeek 2
} }
elseif ($UpdatesInterval -eq 'BiWeekly') elseif ($UpdatesInterval -eq "BiWeekly") {
{ $tasktriggers += New-ScheduledTaskTrigger -Weekly -At $UpdatesAtTime -DaysOfWeek 2 -WeeksInterval 2
$taskTriggers += New-ScheduledTaskTrigger -Weekly -At $UpdatesAtTime -DaysOfWeek 2 -WeeksInterval 2
} }
elseif ($UpdatesInterval -eq 'Monthly') elseif ($UpdatesInterval -eq "Monthly") {
{ $tasktriggers += New-ScheduledTaskTrigger -Weekly -At $UpdatesAtTime -DaysOfWeek 2 -WeeksInterval 4
$taskTriggers += New-ScheduledTaskTrigger -Weekly -At $UpdatesAtTime -DaysOfWeek 2 -WeeksInterval 4
} }
$taskUserPrincipal = New-ScheduledTaskPrincipal -UserId S-1-5-18 -RunLevel Highest $taskUserPrincipal = New-ScheduledTaskPrincipal -UserId S-1-5-18 -RunLevel Highest
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 03:00:00 $taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 03:00:00
# Set up the task, and register it # Set up the task, and register it
if ($taskTriggers) if ($taskTriggers) {
{
$task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings -Trigger $taskTriggers $task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings -Trigger $taskTriggers
} }
else else {
{
$task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings $task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings
} }
$null = Register-ScheduledTask -TaskName 'Winget-AutoUpdate' -InputObject $task -Force Register-ScheduledTask -TaskName 'Winget-AutoUpdate' -InputObject $task -Force | Out-Null
if ($InstallUserContext) if ($InstallUserContext) {
{
# Settings for the scheduled task in User context # Settings for the scheduled task in User context
$taskAction = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\winget-upgrade.ps1`"`"" $taskAction = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\winget-upgrade.ps1`"`""
$taskUserPrincipal = New-ScheduledTaskPrincipal -GroupId S-1-5-11 $taskUserPrincipal = New-ScheduledTaskPrincipal -GroupId S-1-5-11
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 03:00:00 $taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 03:00:00
# Set up the task for user apps # Set up the task for user apps
$task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings $task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings
$null = Register-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -InputObject $task -Force Register-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -InputObject $task -Force | Out-Null
} }
# Settings for the scheduled task for Notifications # Settings for the scheduled task for Notifications
$taskAction = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\winget-notify.ps1`"`"" $taskAction = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\winget-notify.ps1`"`""
$taskUserPrincipal = New-ScheduledTaskPrincipal -GroupId S-1-5-11 $taskUserPrincipal = New-ScheduledTaskPrincipal -GroupId S-1-5-11
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 00:05:00 $taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8 -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 00:05:00
# Set up the task, and register it # Set up the task, and register it
$task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings $task = New-ScheduledTask -Action $taskAction -Principal $taskUserPrincipal -Settings $taskSettings
$null = Register-ScheduledTask -TaskName 'Winget-AutoUpdate-Notify' -InputObject $task -Force Register-ScheduledTask -TaskName 'Winget-AutoUpdate-Notify' -InputObject $task -Force | Out-Null
#Set task readable/runnable for all users #Set task readable/runnable for all users
$scheduler = New-Object -ComObject 'Schedule.Service' $scheduler = New-Object -ComObject "Schedule.Service"
$scheduler.Connect() $scheduler.Connect()
$task = $scheduler.GetFolder('').GetTask('Winget-AutoUpdate') $task = $scheduler.GetFolder("").GetTask("Winget-AutoUpdate")
$sec = $task.GetSecurityDescriptor(0xF) $sec = $task.GetSecurityDescriptor(0xF)
$sec = $sec + '(A;;GRGX;;;AU)' $sec = $sec + '(A;;GRGX;;;AU)'
$task.SetSecurityDescriptor($sec, 0) $task.SetSecurityDescriptor($sec, 0)
# Configure Reg Key # Configure Reg Key
$regPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate' $regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate"
$null = New-Item $regPath -Force New-Item $regPath -Force | Out-Null
$null = New-ItemProperty $regPath -Name DisplayName -Value 'Winget-AutoUpdate (WAU)' -Force New-ItemProperty $regPath -Name DisplayName -Value "Winget-AutoUpdate (WAU)" -Force | Out-Null
$null = New-ItemProperty $regPath -Name DisplayIcon -Value 'C:\Windows\System32\shell32.dll,-16739' -Force New-ItemProperty $regPath -Name DisplayIcon -Value "C:\Windows\System32\shell32.dll,-16739" -Force | Out-Null
$null = New-ItemProperty $regPath -Name DisplayVersion -Value $WAUVersion -Force New-ItemProperty $regPath -Name DisplayVersion -Value $WAUVersion -Force | Out-Null
$null = New-ItemProperty $regPath -Name InstallLocation -Value $WingetUpdatePath -Force New-ItemProperty $regPath -Name InstallLocation -Value $WingetUpdatePath -Force | Out-Null
$null = New-ItemProperty $regPath -Name UninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WingetUpdatePath\WAU-Uninstall.ps1`"" -Force New-ItemProperty $regPath -Name UninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WingetUpdatePath\WAU-Uninstall.ps1`"" -Force | Out-Null
$null = New-ItemProperty $regPath -Name QuietUninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WingetUpdatePath\WAU-Uninstall.ps1`"" -Force New-ItemProperty $regPath -Name QuietUninstallString -Value "powershell.exe -noprofile -executionpolicy bypass -file `"$WingetUpdatePath\WAU-Uninstall.ps1`"" -Force | Out-Null
$null = New-ItemProperty $regPath -Name NoModify -Value 1 -Force New-ItemProperty $regPath -Name NoModify -Value 1 -Force | Out-Null
$null = New-ItemProperty $regPath -Name NoRepair -Value 1 -Force New-ItemProperty $regPath -Name NoRepair -Value 1 -Force | Out-Null
$null = New-ItemProperty $regPath -Name Publisher -Value 'Romanitho' -Force New-ItemProperty $regPath -Name Publisher -Value "Romanitho" -Force | Out-Null
$null = New-ItemProperty $regPath -Name URLInfoAbout -Value 'https://github.com/Romanitho/Winget-AutoUpdate' -Force New-ItemProperty $regPath -Name URLInfoAbout -Value "https://github.com/Romanitho/Winget-AutoUpdate" -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_NotificationLevel -Value $NotificationLevel -Force New-ItemProperty $regPath -Name WAU_NotificationLevel -Value $NotificationLevel -Force | Out-Null
if ($WAUVersion -match '-') if ($WAUVersion -match "-"){
{ New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value 1 -PropertyType DWord -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value 1 -PropertyType DWord -Force
} }
else else {
{ New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value 0 -PropertyType DWord -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_UpdatePrerelease -Value 0 -PropertyType DWord -Force
} }
$null = New-ItemProperty $regPath -Name WAU_PostUpdateActions -Value 0 -PropertyType DWord -Force New-ItemProperty $regPath -Name WAU_PostUpdateActions -Value 0 -PropertyType DWord -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_MaxLogFiles -Value $MaxLogFiles -PropertyType DWord -Force New-ItemProperty $regPath -Name WAU_MaxLogFiles -Value $MaxLogFiles -PropertyType DWord -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_MaxLogSize -Value $MaxLogSize -PropertyType DWord -Force New-ItemProperty $regPath -Name WAU_MaxLogSize -Value $MaxLogSize -PropertyType DWord -Force | Out-Null
if ($DisableWAUAutoUpdate) if ($DisableWAUAutoUpdate) {
{ New-ItemProperty $regPath -Name WAU_DisableAutoUpdate -Value 1 -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_DisableAutoUpdate -Value 1 -Force
} }
if ($UseWhiteList) if ($UseWhiteList) {
{ New-ItemProperty $regPath -Name WAU_UseWhiteList -Value 1 -PropertyType DWord -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_UseWhiteList -Value 1 -PropertyType DWord -Force
} }
if (!$RunOnMetered) if (!$RunOnMetered) {
{ New-ItemProperty $regPath -Name WAU_DoNotRunOnMetered -Value 1 -PropertyType DWord -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_DoNotRunOnMetered -Value 1 -PropertyType DWord -Force
} }
if ($ListPath) if ($ListPath) {
{ New-ItemProperty $regPath -Name WAU_ListPath -Value $ListPath -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_ListPath -Value $ListPath -Force
} }
if ($ModsPath) if ($ModsPath) {
{ New-ItemProperty $regPath -Name WAU_ModsPath -Value $ModsPath -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_ModsPath -Value $ModsPath -Force
} }
if ($AzureBlobSASURL) if ($AzureBlobSASURL) {
{ New-ItemProperty $regPath -Name WAU_AzureBlobSASURL -Value $AzureBlobSASURL -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_AzureBlobSASURL -Value $AzureBlobSASURL -Force
} }
if ($BypassListForUsers) if ($BypassListForUsers) {
{ New-ItemProperty $regPath -Name WAU_BypassListForUsers -Value 1 -PropertyType DWord -Force | Out-Null
$null = New-ItemProperty $regPath -Name WAU_BypassListForUsers -Value 1 -PropertyType DWord -Force
} }
#Log file and symlink initialization #Log file and symlink initialization
@ -513,173 +427,136 @@ function Install-WingetAutoUpdate
Start-Init Start-Init
#Security check #Security check
Write-Host -Object "`nChecking Mods Directory:" -ForegroundColor Yellow Write-host "`nChecking Mods Directory:" -ForegroundColor Yellow
. "$WingetUpdatePath\functions\Invoke-ModsProtect.ps1" . "$WingetUpdatePath\functions\Invoke-ModsProtect.ps1"
$Protected = Invoke-ModsProtect "$WingetUpdatePath\mods" $Protected = Invoke-ModsProtect "$WingetUpdatePath\mods"
if ($Protected -eq $True) if ($Protected -eq $True) {
{ Write-Host "The mods directory is now secured!`n" -ForegroundColor Green
Write-Host -Object "The mods directory is now secured!`n" -ForegroundColor Green
} }
elseif ($Protected -eq $false) elseif ($Protected -eq $False) {
{ Write-Host "The mods directory was already secured!`n" -ForegroundColor Green
Write-Host -Object "The mods directory was already secured!`n" -ForegroundColor Green
} }
else else {
{ Write-Host "Error: The mods directory couldn't be verified as secured!`n" -ForegroundColor Red
Write-Host -Object "Error: The mods directory couldn't be verified as secured!`n" -ForegroundColor Red
} }
#Create Shortcuts #Create Shortcuts
if ($StartMenuShortcut) if ($StartMenuShortcut) {
{ if (!(Test-Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)")) {
if (!(Test-Path -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
{
$null = New-Item -ItemType Directory -Force -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)"
} }
Add-Shortcut 'wscript.exe' "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Check for updated Apps.lnk" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\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 - Check for updated Apps.lnk" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\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" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\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 - Open logs.lnk" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\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" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\user-run.ps1`" -Help`"" "${env:SystemRoot}\System32\shell32.dll,-24" 'Help for WAU...' Add-Shortcut "wscript.exe" "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)\WAU - Web Help.lnk" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\user-run.ps1`" -Help`"" "${env:SystemRoot}\System32\shell32.dll,-24" "Help for WAU..."
} }
if ($DesktopShortcut) if ($DesktopShortcut) {
{ Add-Shortcut "wscript.exe" "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\user-run.ps1`"`"" "${env:SystemRoot}\System32\shell32.dll,-16739" "Manual start of Winget-AutoUpdate (WAU)..."
Add-Shortcut 'wscript.exe' "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" "`"$($WingetUpdatePath)\Invisible.vbs`" `"powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"`"`"$($WingetUpdatePath)\user-run.ps1`"`"" "${env:SystemRoot}\System32\shell32.dll,-16739" 'Manual start of Winget-AutoUpdate (WAU)...'
} }
Write-Host -Object 'WAU Installation succeeded!' -ForegroundColor Green Write-host "WAU Installation succeeded!" -ForegroundColor Green
Start-Sleep -Seconds 1 Start-sleep 1
#Run Winget ? #Run Winget ?
Start-WingetAutoUpdate Start-WingetAutoUpdate
} }
catch catch {
{ Write-host "WAU Installation failed! Run me with admin rights" -ForegroundColor Red
Write-Host -Object 'WAU Installation failed! Run me with admin rights' -ForegroundColor Red Start-sleep 1
Start-Sleep -Seconds 1 return $False
return $false
} }
} }
function Uninstall-WingetAutoUpdate function Uninstall-WingetAutoUpdate {
{
Write-Host -Object "`nUninstalling WAU..." -ForegroundColor Yellow
try Write-Host "`nUninstalling WAU..." -ForegroundColor Yellow
{
try {
#Get registry install location #Get registry install location
$InstallLocation = Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate\' -Name InstallLocation $InstallLocation = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate\" -Name InstallLocation
#Check if installed location exists and delete #Check if installed location exists and delete
if (Test-Path ($InstallLocation)) if (Test-Path ($InstallLocation)) {
{
if (!$NoClean) if (!$NoClean) {
{
Remove-Item $InstallLocation -Force -Recurse Remove-Item $InstallLocation -Force -Recurse
if (Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log") 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:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-updates.log" -Force -ErrorAction SilentlyContinue
} }
if (Test-Path -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log") 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
$null = Remove-Item -Path "${env:ProgramData}\Microsoft\IntuneManagementExtension\Logs\WAU-install.log" -Force -ErrorAction SilentlyContinue
} }
} }
else else {
{
#Keep critical files #Keep critical files
Get-ChildItem -Path $InstallLocation -Exclude *.txt, mods, logs | Remove-Item -Recurse -Force Get-ChildItem -Path $InstallLocation -Exclude *.txt, mods, logs | Remove-Item -Recurse -Force
} }
Get-ScheduledTask -TaskName 'Winget-AutoUpdate' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false Get-ScheduledTask -TaskName "Winget-AutoUpdate" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$False
Get-ScheduledTask -TaskName 'Winget-AutoUpdate-Notify' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false Get-ScheduledTask -TaskName "Winget-AutoUpdate-Notify" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$False
Get-ScheduledTask -TaskName 'Winget-AutoUpdate-UserContext' -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false 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 & reg delete "HKCR\AppUserModelId\Windows.SystemToast.Winget.Notification" /f | Out-Null
$null = & "$env:windir\system32\reg.exe" delete 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate' /f & reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Winget-AutoUpdate" /f | Out-Null
if ((Test-Path -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)")) if ((Test-Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)")) {
{ Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force | Out-Null
$null = Remove-Item -Path "${env:ProgramData}\Microsoft\Windows\Start Menu\Programs\Winget-AutoUpdate (WAU)" -Recurse -Force
} }
if ((Test-Path -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk")) if ((Test-Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk")) {
{ Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force | Out-Null
$null = Remove-Item -Path "${env:Public}\Desktop\WAU - Check for updated Apps.lnk" -Force
} }
Write-Host -Object 'Uninstallation succeeded!' -ForegroundColor Green Write-host "Uninstallation succeeded!" -ForegroundColor Green
Start-Sleep -Seconds 1 Start-sleep 1
} }
else else {
{ Write-host "$InstallLocation not found! Uninstallation failed!" -ForegroundColor Red
Write-Host -Object "$InstallLocation not found! Uninstallation failed!" -ForegroundColor Red
} }
} }
catch catch {
{ Write-host "Uninstallation failed! Run as admin ?" -ForegroundColor Red
Write-Host -Object 'Uninstallation failed! Run as admin ?' -ForegroundColor Red Start-sleep 1
Start-Sleep -Seconds 1
} }
} }
function Start-WingetAutoUpdate function Start-WingetAutoUpdate {
{
#If -DoNotUpdate is true, skip. #If -DoNotUpdate is true, skip.
if (!($DoNotUpdate)) if (!($DoNotUpdate)) {
{
#If -Silent, run Winget-AutoUpdate now #If -Silent, run Winget-AutoUpdate now
if ($Silent) if ($Silent) {
{
$RunWinget = 1 $RunWinget = 1
} }
#Ask for WingetAutoUpdate #Ask for WingetAutoUpdate
else else {
{ $MsgBoxTitle = "Winget-AutoUpdate"
$MsgBoxTitle = 'Winget-AutoUpdate' $MsgBoxContent = "Would you like to run Winget-AutoUpdate now?"
$MsgBoxContent = 'Would you like to run Winget-AutoUpdate now?'
$MsgBoxTimeOut = 60 $MsgBoxTimeOut = 60
$MsgBoxReturn = (New-Object -ComObject 'Wscript.Shell').Popup($MsgBoxContent, $MsgBoxTimeOut, $MsgBoxTitle, 4 + 32) $MsgBoxReturn = (New-Object -ComObject "Wscript.Shell").Popup($MsgBoxContent, $MsgBoxTimeOut, $MsgBoxTitle, 4 + 32)
if ($MsgBoxReturn -ne 7) if ($MsgBoxReturn -ne 7) {
{
$RunWinget = 1 $RunWinget = 1
} }
else else {
{
$RunWinget = 0 $RunWinget = 0
} }
} }
if ($RunWinget -eq 1) if ($RunWinget -eq 1) {
{ try {
try Write-host "`nRunning Winget-AutoUpdate..." -ForegroundColor Yellow
{ Get-ScheduledTask -TaskName "Winget-AutoUpdate" -ErrorAction SilentlyContinue | Start-ScheduledTask -ErrorAction SilentlyContinue
Write-Host -Object "`nRunning Winget-AutoUpdate..." -ForegroundColor Yellow while ((Get-ScheduledTask -TaskName "Winget-AutoUpdate").State -ne 'Ready') {
Get-ScheduledTask -TaskName 'Winget-AutoUpdate' -ErrorAction SilentlyContinue | Start-ScheduledTask -ErrorAction SilentlyContinue Start-Sleep 1
while ((Get-ScheduledTask -TaskName 'Winget-AutoUpdate').State -ne 'Ready')
{
Start-Sleep -Seconds 1
} }
} }
catch catch {
{ Write-host "Failed to run Winget-AutoUpdate..." -ForegroundColor Red
Write-Host -Object 'Failed to run Winget-AutoUpdate...' -ForegroundColor Red
} }
} }
} }
else else {
{ Write-host "Skip running Winget-AutoUpdate"
Write-Host -Object 'Skip running Winget-AutoUpdate'
} }
} }
function Add-Shortcut function Add-Shortcut ($Target, $Shortcut, $Arguments, $Icon, $Description) {
{
[CmdletBinding()]
param
(
$Target,
$Shortcut,
$Arguments,
$Icon,
$Description
)
$WScriptShell = New-Object -ComObject WScript.Shell $WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($Shortcut) $Shortcut = $WScriptShell.CreateShortcut($Shortcut)
$Shortcut.TargetPath = $Target $Shortcut.TargetPath = $Target
@ -692,47 +569,43 @@ function Add-Shortcut
<# APP INFO #> <# APP INFO #>
$WAUVersion = Get-Content -Path "$PSScriptRoot\Winget-AutoUpdate\Version.txt" -ErrorAction SilentlyContinue $WAUVersion = Get-Content "$PSScriptRoot\Winget-AutoUpdate\Version.txt" -ErrorAction SilentlyContinue
<# MAIN #> <# MAIN #>
#If running as a 32-bit process on an x64 system, re-launch as a 64-bit process #If running as a 32-bit process on an x64 system, re-launch as a 64-bit process
if ("$env:PROCESSOR_ARCHITEW6432" -ne 'ARM64') if ("$env:PROCESSOR_ARCHITEW6432" -ne "ARM64") {
{ if (Test-Path "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe") {
if (Test-Path -Path "$($env:windir)\SysNative\WindowsPowerShell\v1.0\powershell.exe") Start-Process "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe" -Wait -NoNewWindow -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command $($MyInvocation.line)"
{ Exit $lastexitcode
Start-Process -FilePath "$($env:windir)\SysNative\WindowsPowerShell\v1.0\powershell.exe" -Wait -NoNewWindow -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command $($MyInvocation.line)"
exit $lastexitcode
} }
} }
Write-Host -Object "`n" Write-Host "`n"
Write-Host -Object "`t 888 888 d8888 888 888" -ForegroundColor Magenta Write-Host "`t 888 888 d8888 888 888" -ForegroundColor Magenta
Write-Host -Object "`t 888 o 888 d88888 888 888" -ForegroundColor Magenta Write-Host "`t 888 o 888 d88888 888 888" -ForegroundColor Magenta
Write-Host -Object "`t 888 d8b 888 d88P888 888 888" -ForegroundColor Magenta Write-Host "`t 888 d8b 888 d88P888 888 888" -ForegroundColor Magenta
Write-Host -Object "`t 888 d888b 888 d88P 888 888 888" -ForegroundColor Magenta Write-Host "`t 888 d888b 888 d88P 888 888 888" -ForegroundColor Magenta
Write-Host -Object "`t 888d88888b888 d88P 888 888 888" -ForegroundColor Magenta Write-Host "`t 888d88888b888 d88P 888 888 888" -ForegroundColor Magenta
Write-Host -Object "`t 88888P Y88888 d88P 888 888 888" -ForegroundColor Cyan Write-Host "`t 88888P Y88888 d88P 888 888 888" -ForegroundColor Cyan
Write-Host -Object "`t 8888P Y8888 d88P 888 888 888" -ForegroundColor Magenta Write-Host "`t 8888P Y8888 d88P 888 888 888" -ForegroundColor Magenta
Write-Host -Object "`t 888P Y888 d88P 888 Y8888888P`n" -ForegroundColor Magenta Write-Host "`t 888P Y888 d88P 888 Y8888888P`n" -ForegroundColor Magenta
Write-Host -Object "`t Winget-AutoUpdate $WAUVersion`n" -ForegroundColor Cyan Write-Host "`t Winget-AutoUpdate $WAUVersion`n" -ForegroundColor Cyan
Write-Host -Object "`t https://github.com/Romanitho/Winget-AutoUpdate`n" -ForegroundColor Magenta Write-Host "`t https://github.com/Romanitho/Winget-AutoUpdate`n" -ForegroundColor Magenta
Write-Host -Object "`t________________________________________________________`n`n" Write-Host "`t________________________________________________________`n`n"
if (!$Uninstall) if (!$Uninstall) {
{ Write-host "Installing WAU to $WingetUpdatePath\"
Write-Host -Object "Installing WAU to $WingetUpdatePath\"
Install-Prerequisites Install-Prerequisites
Install-WinGet Install-WinGet
Install-WingetAutoUpdate Install-WingetAutoUpdate
} }
else else {
{ Write-Host "Uninstalling WAU..."
Write-Host -Object 'Uninstalling WAU...'
Uninstall-WingetAutoUpdate Uninstall-WingetAutoUpdate
} }
Remove-Item -Path "$WingetUpdatePath\Version.txt" -Force Remove-Item "$WingetUpdatePath\Version.txt" -Force
Write-Host -Object "`nEnd of process." -ForegroundColor Cyan Write-host "`nEnd of process." -ForegroundColor Cyan
Start-Sleep -Seconds 3 Start-Sleep 3

View File

@ -19,17 +19,13 @@
[CmdletBinding()] [CmdletBinding()]
param( param(
[Switch] [Parameter(Mandatory = $False)] [Switch] $Logs = $false,
$Logs = $False, [Parameter(Mandatory = $False)] [Switch] $Help = $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')) {
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
{
return $True
} }
} }
@ -46,72 +42,61 @@ $Script:WorkingDir = $PSScriptRoot
Get-NotifLocale Get-NotifLocale
#Set common variables #Set common variables
$OnClickAction = ('{0}\logs\updates.log' -f $WorkingDir) $OnClickAction = "$WorkingDir\logs\updates.log"
$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") {
if (Test-Path -Path ('{0}\logs\updates.log' -f $WorkingDir)) Invoke-Item "$WorkingDir\logs\updates.log"
{
Invoke-Item -Path ('{0}\logs\updates.log' -f $WorkingDir)
} }
else else {
{
#Not available yet #Not available yet
$Message = $NotifLocale.local.outputs.output[5].message $Message = $NotifLocale.local.outputs.output[5].message
$MessageType = 'warning' $MessageType = "warning"
Start-NotifTask -Message $Message -MessageType $MessageType -UserRun 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 {
try
{
#Check if WAU is currently running #Check if WAU is currently running
if (Test-WAUisRunning) if (Test-WAUisRunning) {
{
$Message = $NotifLocale.local.outputs.output[8].message $Message = $NotifLocale.local.outputs.output[8].message
$MessageType = 'warning' $MessageType = "warning"
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
break break
} }
#Run scheduled task #Run scheduled task
Get-ScheduledTask -TaskName 'Winget-AutoUpdate' -ErrorAction Stop | Start-ScheduledTask -ErrorAction Stop Get-ScheduledTask -TaskName "Winget-AutoUpdate" -ErrorAction Stop | Start-ScheduledTask -ErrorAction Stop
#Starting check - Send notification #Starting check - Send notification
$Message = $NotifLocale.local.outputs.output[6].message $Message = $NotifLocale.local.outputs.output[6].message
$MessageType = 'info' $MessageType = "info"
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
#Sleep until the task is done #Sleep until the task is done
while (Test-WAUisRunning) While (Test-WAUisRunning) {
{ Start-Sleep 3
Start-Sleep -Seconds 3
} }
#Test if there was a list_/winget_error #Test if there was a list_/winget_error
if (Test-Path -Path ('{0}\logs\error.txt' -f $WorkingDir) -ErrorAction SilentlyContinue) if (Test-Path "$WorkingDir\logs\error.txt") {
{ $MessageType = "error"
$MessageType = 'error' $Critical = Get-Content "$WorkingDir\logs\error.txt" -Raw
$Critical = Get-Content -Path ('{0}\logs\error.txt' -f $WorkingDir) -Raw
$Critical = $Critical.Trim() $Critical = $Critical.Trim()
$Critical = $Critical.Substring(0, [Math]::Min($Critical.Length, 50)) $Critical = $Critical.Substring(0, [Math]::Min($Critical.Length, 50))
$Message = ("Critical:`n{0}..." -f $Critical) $Message = "Critical:`n$Critical..."
} }
else else {
{ $MessageType = "success"
$MessageType = 'success'
$Message = $NotifLocale.local.outputs.output[9].message $Message = $NotifLocale.local.outputs.output[9].message
} }
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
} }
catch catch {
{
#Check failed - Just send notification #Check failed - Just send notification
$Message = $NotifLocale.local.outputs.output[7].message $Message = $NotifLocale.local.outputs.output[7].message
$MessageType = 'error' $MessageType = "error"
Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun Start-NotifTask -Message $Message -MessageType $MessageType -Button1Text $Button1Text -Button1Action $OnClickAction -ButtonDismiss -UserRun
} }
} }

View File

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

View File

@ -1,29 +1,24 @@
#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 -Path "$WAUinstalledPath\config\notif.xml" -Encoding UTF8 -ErrorAction SilentlyContinue) [xml]$NotifConf = Get-Content "$WAUinstalledPath\config\notif.xml" -Encoding UTF8 -ErrorAction SilentlyContinue
if (!($NotifConf)) {
if (!($NotifConf))
{
break break
} }
#Load Assemblies #Load Assemblies
$null = (Add-Type -AssemblyName Windows.Data) [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
$null = (Add-Type -AssemblyName Windows.UI) [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
$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 #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

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

View File

@ -1,40 +1,20 @@
#Function to configure the prefered scope option as Machine #Function to configure the prefered scope option as Machine
function Add-ScopeMachine function Add-ScopeMachine ($SettingsPath) {
{
[CmdletBinding()]
param
(
[string]
$SettingsPath
)
if (Test-Path -Path $SettingsPath -ErrorAction SilentlyContinue) if (Test-Path $SettingsPath) {
{ $ConfigFile = Get-Content -Path $SettingsPath | Where-Object { $_ -notmatch '//' } | ConvertFrom-Json
$ConfigFile = (Get-Content -Path $SettingsPath -ErrorAction SilentlyContinue | Where-Object -FilterScript {
($_ -notmatch '//')
} | ConvertFrom-Json)
} }
if (!$ConfigFile) {
$ConfigFile = @{}
}
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,22 +1,6 @@
#Function to create shortcuts #Function to create shortcuts
function Add-Shortcut function Add-Shortcut ($Target, $Shortcut, $Arguments, $Icon, $Description) {
{ $WScriptShell = New-Object -ComObject WScript.Shell
[CmdletBinding()]
param
(
[string]
$Target,
[string]
$Shortcut,
[string]
$Arguments,
[string]
$Icon,
[string]
$Description
)
$WScriptShell = (New-Object -ComObject WScript.Shell)
$Shortcut = $WScriptShell.CreateShortcut($Shortcut) $Shortcut = $WScriptShell.CreateShortcut($Shortcut)
$Shortcut.TargetPath = $Target $Shortcut.TargetPath = $Target
$Shortcut.Arguments = $Arguments $Shortcut.Arguments = $Arguments

View File

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

View File

@ -1,59 +1,50 @@
#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 Function Get-AZCopy ($WingetUpdatePath) {
{
[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 ('{0}\azcopy.exe' -f $WingetUpdatePath) -PathType Leaf -ErrorAction SilentlyContinue) if (Test-Path -Path "$WingetUpdatePath\azcopy.exe" -PathType Leaf) {
{
$AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v $AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v
$AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value $AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value
Write-ToLog -LogMsg ('AZCopy version {0} found' -f $AZCopyCurrentVersion) Write-ToLog "AZCopy version $AZCopyCurrentVersion found"
} }
else else {
{ Write-ToLog "AZCopy not already installed"
Write-ToLog -LogMsg 'AZCopy not already installed' $AZCopyCurrentVersion = "0.0.0"
$AZCopyCurrentVersion = '0.0.0'
} }
if (([version]$AZCopyCurrentVersion) -lt ([version]$AZCopyLatestVersion)) if (([version] $AZCopyCurrentVersion) -lt ([version] $AZCopyLatestVersion)) {
{ Write-ToLog "Installing version $AZCopyLatestVersion of AZCopy"
Write-ToLog -LogMsg ('Installing version {0} of AZCopy' -f $AZCopyLatestVersion) Invoke-WebRequest -Uri $AZCopyLink -UseBasicParsing -OutFile "$WingetUpdatePath\azcopyv10.zip"
$null = (Invoke-WebRequest -Uri $AZCopyLink -UseBasicParsing -OutFile ('{0}\azcopyv10.zip' -f $WingetUpdatePath)) Write-ToLog "Extracting AZCopy zip file"
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))
if ($AZCopyPathSearch -is [array]) Expand-archive -Path "$WingetUpdatePath\azcopyv10.zip" -Destinationpath "$WingetUpdatePath" -Force
{
$AZCopyPathSearch = Resolve-Path -path "$WingetUpdatePath\azcopy_*"
if ($AZCopyPathSearch -is [array]) {
$AZCopyEXEPath = $AZCopyPathSearch[$AZCopyPathSearch.Length - 1] $AZCopyEXEPath = $AZCopyPathSearch[$AZCopyPathSearch.Length - 1]
} }
else else {
{
$AZCopyEXEPath = $AZCopyPathSearch $AZCopyEXEPath = $AZCopyPathSearch
} }
Write-ToLog -LogMsg "Copying 'azcopy.exe' to main folder" Write-ToLog "Copying 'azcopy.exe' to main folder"
$null = (Copy-Item -Path ('{0}\azcopy.exe' -f $AZCopyEXEPath) -Destination ('{0}\' -f $WingetUpdatePath) -Force -Confirm:$false) Copy-Item "$AZCopyEXEPath\azcopy.exe" -Destination "$WingetUpdatePath\"
Write-ToLog -LogMsg 'Removing temporary AZCopy files'
$null = (Remove-Item -Path $AZCopyEXEPath -Recurse -Force -Confirm:$false) Write-ToLog "Removing temporary AZCopy files"
$null = (Remove-Item -Path ('{0}\azcopyv10.zip' -f $WingetUpdatePath) -Force -Confirm:$false) Remove-Item -Path $AZCopyEXEPath -Recurse
Remove-Item -Path "$WingetUpdatePath\azcopyv10.zip"
$AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v $AZCopyCurrentVersion = & "$WingetUpdatePath\azcopy.exe" -v
$AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value $AZCopyCurrentVersion = $AZCopyVersionRegex.Match($AZCopyCurrentVersion).Value
Write-ToLog -LogMsg ('AZCopy version {0} installed' -f $AZCopyCurrentVersion) Write-ToLog "AZCopy version $AZCopyCurrentVersion installed"
} }
} }

View File

@ -1,18 +1,11 @@
#Get the winget App Information #Get the winget App Information
function Get-AppInfo Function Get-AppInfo ($AppID) {
{
#Get AppID Info #Get AppID Info
[CmdletBinding()] $String = & $winget show $AppID --accept-source-agreements -s winget | Out-String
param
(
[string]
$AppID
)
$String = (& $winget show $AppID --accept-source-agreements -s winget | Out-String)
#Search for Release Note info #Search for Release Note info
$ReleaseNote = [regex]::match($String, '(?<=Release Notes Url: )(.*)(?=\n)').Groups[0].Value $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 ($GPOList) {
{
if (Test-Path -Path 'HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList' -ErrorAction SilentlyContinue) if (Test-Path "HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList") {
{
$Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList\' $Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList\'
$ValueNames = (Get-Item -Path 'HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList').Property $ValueNames = (Get-Item -Path "HKLM:\SOFTWARE\Policies\Romanitho\Winget-AutoUpdate\BlackList").Property
foreach ($ValueName in $ValueNames) foreach ($ValueName in $ValueNames) {
{
$AppIDs = [Microsoft.Win32.Registry]::GetValue($Key, $ValueName, $false) $AppIDs = [Microsoft.Win32.Registry]::GetValue($Key, $ValueName, $false)
[PSCustomObject]@{ [PSCustomObject]@{
Value = $ValueName Value = $ValueName
Data = $AppIDs.Trim() Data = $AppIDs.Trim()
} }
} }
}
return $AppIDs
}
elseif (Test-Path "$WorkingDir\excluded_apps.txt") {
return (Get-Content -Path "$WorkingDir\excluded_apps.txt").Trim() | Where-Object { $_.length -gt 0 }
} }
return $AppIDs
}
elseif (Test-Path -Path ('{0}\excluded_apps.txt' -f $WorkingDir) -ErrorAction SilentlyContinue)
{
return (Get-Content -Path ('{0}\excluded_apps.txt' -f $WorkingDir)).Trim() | Where-Object -FilterScript {
$_.length -gt 0
}
}
} }

View File

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

View File

@ -1,31 +1,28 @@
#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 = ('{0}\locale\{1}.xml' -f $WorkingDir, $OSLocale.Name) $TestOSLocalPath = "$WorkingDir\locale\$($OSLocale.Name).xml"
#Set OS Local if file exists #Set OS Local if file exists
if (Test-Path -Path $TestOSLocalPath -ErrorAction SilentlyContinue) if (Test-Path $TestOSLocalPath) {
{
$LocaleDisplayName = $OSLocale.DisplayName $LocaleDisplayName = $OSLocale.DisplayName
$LocaleFile = $TestOSLocalPath $LocaleFile = $TestOSLocalPath
} }
else
{
#Set English if file doesn't exist #Set English if file doesn't exist
$LocaleDisplayName = 'English' else {
$LocaleFile = ('{0}\locale\en.xml' -f $WorkingDir) $LocaleDisplayName = "English"
$LocaleFile = "$WorkingDir\locale\en.xml"
} }
#Get locale XML file content #Get locale XML file content
[xml]$Script:NotifLocale = (Get-Content -Path $LocaleFile -Encoding UTF8 -ErrorAction SilentlyContinue) [xml]$Script:NotifLocale = Get-Content $LocaleFile -Encoding UTF8 -ErrorAction SilentlyContinue
#Rerturn langague display name #Rerturn langague display name
return $LocaleDisplayName Return $LocaleDisplayName
} }

View File

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

View File

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

View File

@ -1,52 +1,40 @@
#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 -Path "$env:ProgramFiles\WindowsApps\Microsoft.DesktopAppInstaller_*_*__8wekyb3d8bbwe" | Sort-Object -Property { $ResolveWingetPath = Resolve-Path "$env:ProgramFiles\WindowsApps\Microsoft.DesktopAppInstaller_*_*__8wekyb3d8bbwe" | Sort-Object { [version]($_.Path -replace '^[^\d]+_((\d+\.)*\d+)_.*', '$1') }
[version]($_.Path -replace '^[^\d]+_((\d+\.)*\d+)_.*', '$1')
})
if ($ResolveWingetPath) if ($ResolveWingetPath) {
{
#If multiple version, pick last one #If multiple version, pick last one
$WingetPath = $ResolveWingetPath[-1].Path $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 ((([Security.Principal.WindowsIdentity]::GetCurrent().User) -eq 'S-1-5-18') -or ($WingetPath)) if((([System.Security.Principal.WindowsIdentity]::GetCurrent().User) -eq "S-1-5-18") -or ($WingetPath)){
{ if (Test-Path "$WingetPath\winget.exe") {
if (Test-Path -Path ('{0}\winget.exe' -f $WingetPath) -ErrorAction SilentlyContinue) $Script:Winget = "$WingetPath\winget.exe"
{
$Script:Winget = ('{0}\winget.exe' -f $WingetPath)
} }
} }else{
else
{
#Get Winget Location in User context #Get Winget Location in User context
$WingetCmd = (Get-Command -Name winget.exe -ErrorAction SilentlyContinue) $WingetCmd = Get-Command winget.exe -ErrorAction SilentlyContinue
if ($WingetCmd) {
if ($WingetCmd)
{
$Script:Winget = $WingetCmd.Source $Script:Winget = $WingetCmd.Source
} }
} }
if (!($Script:Winget)) If(!($Script:Winget)){
{ Write-ToLog "Winget not installed or detected !" "Red"
Write-ToLog 'Winget not installed or detected !' 'Red'
return $false return $false
} }
#Run winget to list apps and accept source agrements (necessary on first run) #Run winget to list apps and accept source agrements (necessary on first run)
$null = (& $Winget list --accept-source-agreements -s winget) & $Winget list --accept-source-agreements -s winget | Out-Null
#Log Winget installed version #Log Winget installed version
$WingetVer = & $Winget --version $WingetVer = & $Winget --version
Write-ToLog ('Winget Version: {0}' -f $WingetVer) Write-ToLog "Winget Version: $WingetVer"
return $true return $true

View File

@ -1,7 +1,6 @@
#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 { class Software {
[string]$Name [string]$Name
[string]$Id [string]$Id
@ -10,23 +9,19 @@ function Get-WingetOutdatedApps
} }
#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 -FilterScript { $lines = $upgradeResult.Split([Environment]::NewLine) | Where-Object { $_ }
$_
}
# 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++
} }
@ -43,13 +38,9 @@ function Get-WingetOutdatedApps
# 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++) {
for ($i = $fl + 2; $i -lt $lines.Length; $i++) $line = $lines[$i] -replace "[\u2026]", " " #Fix "..." in long names
{ if ($line.StartsWith("-----")) {
$line = $lines[$i] -replace '[\u2026]', ' ' #Fix "..." in long names
if ($line.StartsWith('-----'))
{
#Get header line #Get header line
$fl = $i - 1 $fl = $i - 1
@ -61,10 +52,8 @@ function Get-WingetOutdatedApps
$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
} }
#(Alphanumeric | Literal . | Alphanumeric) - the only unique thing in common for lines with applications #(Alphanumeric | Literal . | Alphanumeric) - the only unique thing in common for lines with applications
if ($line -match '\w\.\w') if ($line -match "\w\.\w") {
{
$software = [Software]::new() $software = [Software]::new()
#Manage non latin characters #Manage non latin characters
$nameDeclination = $($line.Substring(0, $idStart) -replace '[\u4e00-\u9fa5]', '**').Length - $line.Substring(0, $idStart).Length $nameDeclination = $($line.Substring(0, $idStart) -replace '[\u4e00-\u9fa5]', '**').Length - $line.Substring(0, $idStart).Length
@ -78,15 +67,10 @@ function Get-WingetOutdatedApps
} }
#If current user is not system, remove system apps from list #If current user is not system, remove system apps from list
if ($IsSystem -eq $false) if ($IsSystem -eq $false) {
{ $SystemApps = Get-Content -Path "$WorkingDir\winget_system_apps.txt"
$SystemApps = Get-Content -Path ('{0}\winget_system_apps.txt' -f $WorkingDir) $upgradeList = $upgradeList | Where-Object { $SystemApps -notcontains $_.Id }
$upgradeList = $upgradeList | Where-Object -FilterScript {
$SystemApps -notcontains $_.Id
}
} }
return $upgradeList | Sort-Object -Property { return $upgradeList | Sort-Object { Get-Random }
Get-Random
}
} }

View File

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

View File

@ -1,7 +1,6 @@
#Function to rotate the logs #Function to rotate the logs
function Invoke-LogRotation function Invoke-LogRotation ($LogFile, $MaxLogFiles, $MaxLogSize) {
{
<# <#
.SYNOPSIS .SYNOPSIS
Handle log rotation. Handle log rotation.
@ -13,106 +12,84 @@ function Invoke-LogRotation
Date: 21.11.2014 Date: 21.11.2014
Version: 1.0 Version: 1.0
#> #>
param
(
[string]
$LogFile,
[int]
$MaxLogFiles,
[int]
$MaxLogSize
)
try try {
{
# get current size of log file # get current size of log file
$currentSize = (Get-Item -Path $LogFile).Length $currentSize = (Get-Item $LogFile).Length
# get log name # get log name
$logFileName = (Split-Path -Path $LogFile -Leaf) $logFileName = Split-Path $LogFile -Leaf
$logFilePath = (Split-Path -Path $LogFile) $logFilePath = Split-Path $LogFile
$logFileNameWithoutExtension = [IO.Path]::GetFileNameWithoutExtension($logFileName) $logFileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($logFileName)
$logFileNameExtension = [IO.Path]::GetExtension($logFileName) $logFileNameExtension = [System.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 # construct name of archived log file
$newLogFileName = $logFileNameWithoutExtension + (Get-Date -Format 'yyyyMMddHHmmss').ToString() + $logFileNameExtension $newLogFileName = $logFileNameWithoutExtension + (Get-Date -Format 'yyyyMMddHHmmss').ToString() + $logFileNameExtension
# copy old log file to new using the archived name constructed above # copy old log file to new using the archived name constructed above
$null = (Copy-Item -Path $LogFile -Destination (Join-Path -Path (Split-Path -Path $LogFile) -ChildPath $newLogFileName)) Copy-Item -Path $LogFile -Destination (Join-Path (Split-Path $LogFile) $newLogFileName)
# Create a new log file # Create a new log file
try try {
{ Remove-Item -Path $LogFile -Force
$null = (Remove-Item -Path $LogFile -Force -Confirm:$False -ErrorAction SilentlyContinue) New-Item -ItemType File -Path $LogFile -Force
$null = (New-Item -ItemType File -Path $LogFile -Force -Confirm:$False -ErrorAction SilentlyContinue)
#Set ACL for users on logfile #Set ACL for users on logfile
$NewAcl = (Get-Acl -Path $LogFile) $NewAcl = Get-Acl -Path $LogFile
$identity = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList S-1-5-11) $identity = New-Object System.Security.Principal.SecurityIdentifier S-1-5-11
$fileSystemRights = 'Modify' $fileSystemRights = "Modify"
$type = 'Allow' $type = "Allow"
$fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type $fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type
$fileSystemAccessRule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList) $fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList
$NewAcl.SetAccessRule($fileSystemAccessRule) $NewAcl.SetAccessRule($fileSystemAccessRule)
$null = (Set-Acl -Path $LogFile -AclObject $NewAcl) Set-Acl -Path $LogFile -AclObject $NewAcl
} }
catch catch {
{ Return $False
return $False
} }
# if MaxLogFiles is 0 don't delete any old archived log files # if MaxLogFiles is 0 don't delete any old archived log files
if (-not ($MaxLogFiles -eq 0)) if (-not($MaxLogFiles -eq 0)) {
{
# set filter to search for archived log files # set filter to search for archived log files
$archivedLogFileFilter = $logFileNameWithoutExtension + '??????????????' + $logFileNameExtension $archivedLogFileFilter = $logFileNameWithoutExtension + '??????????????' + $logFileNameExtension
# get archived log files # get archived log files
$oldLogFiles = (Get-Item -Path "$(Join-Path -Path $logFilePath -ChildPath $archivedLogFileFilter)") $oldLogFiles = Get-Item -Path "$(Join-Path -Path $logFilePath -ChildPath $archivedLogFileFilter)"
if ([bool]$oldLogFiles) if ([bool]$oldLogFiles) {
{
# compare found log files to MaxLogFiles parameter of the log object, and delete oldest until we are # compare found log files to MaxLogFiles parameter of the log object, and delete oldest until we are
# back to the correct number # back to the correct number
if (($oldLogFiles.Count + 1) -gt $MaxLogFiles) if (($oldLogFiles.Count + 1) -gt $MaxLogFiles) {
{
[int]$numTooMany = (($oldLogFiles.Count) + 1) - $MaxLogFiles [int]$numTooMany = (($oldLogFiles.Count) + 1) - $MaxLogFiles
$null = ($oldLogFiles | Sort-Object -Property 'LastWriteTime' | Select-Object -First $numTooMany | Remove-Item -Force -Confirm:$False -ErrorAction SilentlyContinue) $oldLogFiles | Sort-Object 'LastWriteTime' | Select-Object -First $numTooMany | Remove-Item
} }
} }
} }
#Log Header #Log Header
$Log = "##################################################`n# CHECK FOR APP UPDATES - $(Get-Date -Format (Get-Culture).DateTimeFormat.ShortDatePattern)`n##################################################" $Log = "##################################################`n# CHECK FOR APP UPDATES - $(Get-Date -Format (Get-culture).DateTimeFormat.ShortDatePattern)`n##################################################"
$null = ($Log | Out-File -FilePath $LogFile -Append -Force) $Log | out-file -filepath $LogFile -Append
Write-ToLog -LogMsg 'Running in System context' 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"
if ($ActivateGPOManagement) Return $True
{
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 catch {
{ Return $False
return $False
} }
} }

View File

@ -2,81 +2,64 @@
#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 function Invoke-ModsProtect ($ModsPath) {
{ try {
[CmdletBinding()] $directory = Get-Item -Path $ModsPath -ErrorAction SilentlyContinue
param $acl = Get-Acl -Path $directory.FullName
(
[string]
$ModsPath
)
try
{
$directory = (Get-Item -Path $ModsPath -ErrorAction SilentlyContinue)
$acl = (Get-Acl -Path $directory.FullName)
#Local Users - S-1-5-32-545 #Local Users - S-1-5-32-545
$userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-32-545')) $userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-545")
#Translate SID to Locale Name #Translate SID to Locale Name
$ntAccount = $userSID.Translate([Security.Principal.NTAccount]) $ntAccount = $userSID.Translate([System.Security.Principal.NTAccount])
$userName = $ntAccount.Value $userName = $ntAccount.Value
$userRights = [Security.AccessControl.FileSystemRights]'Write' $userRights = [System.Security.AccessControl.FileSystemRights]"Write"
$hasWriteAccess = $False $hasWriteAccess = $False
foreach ($access in $acl.Access) foreach ($access in $acl.Access) {
{ if ($access.IdentityReference.Value -eq $userName -and $access.FileSystemRights -eq $userRights) {
if ($access.IdentityReference.Value -eq $userName -and $access.FileSystemRights -eq $userRights)
{
$hasWriteAccess = $True $hasWriteAccess = $True
break break
} }
} }
if ($hasWriteAccess) if ($hasWriteAccess) {
{
#Disable inheritance #Disable inheritance
$acl.SetAccessRuleProtection($True, $True) $acl.SetAccessRuleProtection($True, $True)
# Remove any existing rules # Remove any existing rules
$acl.Access | ForEach-Object -Process { $acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) }
$acl.RemoveAccessRule($_)
}
#SYSTEM Full - S-1-5-18 #SYSTEM Full - S-1-5-18
$userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-18')) $userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-18")
$rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule) $acl.SetAccessRule($rule)
# Save the updated ACL # Save the updated ACL
$null = (Set-Acl -Path $directory.FullName -AclObject $acl) Set-Acl -Path $directory.FullName -AclObject $acl
#Administrators Full - S-1-5-32-544 #Administrators Full - S-1-5-32-544
$acl = (Get-Acl -Path $directory.FullName) $acl = Get-Acl -Path $directory.FullName
$userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-32-544')) $userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-544")
$rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule) $acl.SetAccessRule($rule)
$null = (Set-Acl -Path $directory.FullName -AclObject $acl) Set-Acl -Path $directory.FullName -AclObject $acl
#Local Users ReadAndExecute - S-1-5-32-545 S-1-5-11 #Local Users ReadAndExecute - S-1-5-32-545 S-1-5-11
$acl = (Get-Acl -Path $directory.FullName) $acl = Get-Acl -Path $directory.FullName
$userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-32-545')) $userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-545")
$rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule) $acl.SetAccessRule($rule)
$null = (Set-Acl -Path $directory.FullName -AclObject $acl) Set-Acl -Path $directory.FullName -AclObject $acl
#Authenticated Users ReadAndExecute - S-1-5-11 #Authenticated Users ReadAndExecute - S-1-5-11
$acl = (Get-Acl -Path $directory.FullName) $acl = Get-Acl -Path $directory.FullName
$userSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('S-1-5-11')) $userSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-11")
$rule = (New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($userSID, 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userSID, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule) $acl.SetAccessRule($rule)
$null = (Set-Acl -Path $directory.FullName -AclObject $acl) Set-Acl -Path $directory.FullName -AclObject $acl
return $True return $True
} }
return $False return $False
} }
catch catch {
{ return "Error"
return 'Error'
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,50 +1,34 @@
#Function to check if modification exists within 'mods' directory #Function to check if modification exists within 'mods' directory
function Test-Mods function Test-Mods ($app) {
{
# 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)
if (Test-Path -Path ('{0}\{1}-*' -f $Mods, $app) -ErrorAction SilentlyContinue) $Mods = "$WorkingDir\mods"
{ if (Test-Path "$Mods\$app-*") {
if (Test-Path -Path ('{0}\{1}-preinstall.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue) if (Test-Path "$Mods\$app-preinstall.ps1") {
{ $ModsPreInstall = "$Mods\$app-preinstall.ps1"
$ModsPreInstall = ('{0}\{1}-preinstall.ps1' -f $Mods, $app)
} }
if (Test-Path "$Mods\$app-override.txt") {
if (Test-Path -Path ('{0}\{1}-override.txt' -f $Mods, $app) -ErrorAction SilentlyContinue) $ModsOverride = Get-Content "$Mods\$app-override.txt" -Raw
{
$ModsOverride = Get-Content -Path ('{0}\{1}-override.txt' -f $Mods, $app) -Raw
} }
if (Test-Path "$Mods\$app-install.ps1") {
if (Test-Path -Path ('{0}\{1}-install.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue) $ModsInstall = "$Mods\$app-install.ps1"
{ $ModsUpgrade = "$Mods\$app-install.ps1"
$ModsInstall = ('{0}\{1}-install.ps1' -f $Mods, $app)
$ModsUpgrade = ('{0}\{1}-install.ps1' -f $Mods, $app)
} }
if (Test-Path "$Mods\$app-upgrade.ps1") {
if (Test-Path -Path ('{0}\{1}-upgrade.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue) $ModsUpgrade = "$Mods\$app-upgrade.ps1"
{
$ModsUpgrade = ('{0}\{1}-upgrade.ps1' -f $Mods, $app)
} }
if (Test-Path "$Mods\$app-installed.ps1") {
if (Test-Path -Path ('{0}\{1}-installed.ps1' -f $Mods, $app) -ErrorAction SilentlyContinue) $ModsInstalled = "$Mods\$app-installed.ps1"
{
$ModsInstalled = ('{0}\{1}-installed.ps1' -f $Mods, $app)
} }
} }
return $ModsPreInstall, $ModsOverride, $ModsUpgrade, $ModsInstall, $ModsInstalled return $ModsPreInstall, $ModsOverride, $ModsUpgrade, $ModsInstall, $ModsInstalled
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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