2026-06-21 18:47:52 +02:00
<#
. SYNOPSIS
Removes one or more Windows app packages based on the target scope.
.PARAMETER appsList
An array of app package identifiers to remove (e.g. 'Microsoft.BingNews').
. EXAMPLE
2026-07-19 22:06:07 +02:00
Remove-SelectedApps @('Microsoft.BingNews', 'Microsoft.BingWeather')
2026-06-21 18:47:52 +02:00
. EXAMPLE
2026-07-19 22:06:07 +02:00
Remove-SelectedApps -appsList (Generate-AppsList)
2026-08-24 20:34:50 +02:00
. OUTPUTS
System.Boolean. $true when all removals can be confirmed; otherwise $false.
2026-06-21 18:47:52 +02:00
#>
2026-07-19 22:06:07 +02:00
function Remove-SelectedApps {
2026-03-07 20:28:48 +01:00
param (
$appslist
)
2026-06-22 02:30:31 +07:00
if ( $script:Params . ContainsKey ( "WhatIf" )) {
foreach ( $app in $appslist ) {
Write-Host "[WhatIf] Remove App Package: $app " -ForegroundColor Cyan
}
2026-08-24 20:34:50 +02:00
return $true
2026-06-22 02:30:31 +07:00
}
2026-08-24 20:34:50 +02:00
$failuresBefore = $script:AppRemovalFailures
2026-07-19 22:06:07 +02:00
$targetUser = Get-TargetUserForAppRemoval
2026-03-07 20:28:48 +01:00
$appCount = @ ( $appsList ). Count
2026-06-22 22:13:01 +02:00
$appIndex = 0
2026-03-23 22:59:04 +01:00
$edgeIds = @ ( 'Microsoft.Edge' , 'XPFFTQ037JWMHS' )
2026-06-22 22:13:01 +02:00
$wingetRemovedApps = @ ()
2026-08-12 15:56:29 +02:00
$wingetRemovalFailures = @ {}
2026-10-12 23:53:08 +02:00
if ( -not $script:WingetDeferredRemovals ) { $script:WingetDeferredRemovals = @ {} }
2026-03-07 20:28:48 +01:00
Foreach ( $app in $appsList ) {
2026-08-24 20:34:50 +02:00
if ( $script:CancelRequested ) { return $false }
2026-03-07 20:28:48 +01:00
$appIndex ++
if ( $script:ApplySubStepCallback -and $appCount -gt 1 ) {
2026-09-10 21:18:43 +05:30
& $script:ApplySubStepCallback ( Get-Translation -Key 'RemovingAppsSubStep' -FormatArgs @ ( $appIndex , $appCount )) $appIndex $appCount
2026-06-22 22:13:01 +02:00
}
2026-10-12 23:53:08 +02:00
if ( $script:WingetDeferredRemovals . ContainsKey ( $app )) {
Write-Host "Skipping $app because its uninstall is already scheduled."
continue
}
2026-06-10 21:00:07 +02:00
Write-Host "Removing $app "
2026-03-07 20:28:48 +01:00
2026-06-22 22:13:01 +02:00
if (( Get-AppRemovalMethod $app ) -eq 'WinGet' ) {
2026-10-12 23:53:08 +02:00
$schedulingFailed = $false
$removalSucceeded = Remove-WinGetApp -app $app -SchedulingFailed ([ ref ] $schedulingFailed )
2026-08-24 20:34:50 +02:00
$wingetRemovedApps += $app
2026-10-12 23:53:08 +02:00
if ( $schedulingFailed -or (( $script:Params . ContainsKey ( 'User' ) -or $script:Params . ContainsKey ( 'Sysprep' )) -and -not $removalSucceeded )) {
2026-08-12 15:56:29 +02:00
$wingetRemovalFailures [ $app ] = $true
}
2026-06-22 22:13:01 +02:00
}
else {
2026-08-12 15:56:29 +02:00
if ( -not ( Remove-AppxApp -app $app -targetUser $targetUser )) {
$script:AppRemovalFailures ++
}
2026-06-22 22:13:01 +02:00
}
}
2026-07-14 23:06:40 +03:00
if ( $script:CancelRequested ) {
2026-08-24 20:34:50 +02:00
return $false
2026-06-22 22:13:01 +02:00
}
# Check whether any winget-removed apps are still present, and report errors for each one.
2026-10-12 23:53:08 +02:00
if ( $wingetRemovedApps . Count -gt 0 ) {
$wingetRemovedApps = @ ( $wingetRemovedApps | Where-Object { -not $script:WingetDeferredRemovals . ContainsKey ( $_ ) })
}
2026-07-14 23:06:40 +03:00
if ( $wingetRemovedApps . Count -gt 0 ) {
2026-07-19 22:06:07 +02:00
$postRemovalList = if ( $script:WingetInstalled ) { Get-WingetInstalledApps -TimeOut 10 -NonBlocking } else { $null }
2026-07-14 23:06:40 +03:00
$edgeForceRemoveRequested = $false
2026-08-24 20:34:50 +02:00
$edgeForceRemoveSucceeded = $false
2026-07-14 23:06:40 +03:00
2026-08-12 15:56:29 +02:00
if ( $null -eq $postRemovalList ) {
$script:AppRemovalVerificationUnavailable = $true
2026-08-24 20:34:50 +02:00
foreach ( $app in $wingetRemovedApps ) {
$wingetRemovalFailures [ $app ] = $true
}
2026-08-12 15:56:29 +02:00
}
else {
foreach ( $app in $wingetRemovedApps ) {
if ( -not ( Test-AppInWingetList -appId $app -InstalledList $postRemovalList )) {
continue
2026-07-14 23:06:40 +03:00
}
2026-08-12 15:56:29 +02:00
if ( $edgeIds -contains $app ) {
Write-Host "Unable to uninstall Microsoft Edge via WinGet" -ForegroundColor Red
if ( -not $edgeForceRemoveRequested ) {
$edgeForceRemoveRequested = $true
2026-08-24 20:34:50 +02:00
$edgeForceRemoveSucceeded = Request-EdgeForceRemove
}
if ( $edgeForceRemoveSucceeded ) {
continue
2026-08-12 15:56:29 +02:00
}
}
else {
Write-Host "Unable to uninstall $app via WinGet" -ForegroundColor Red
}
$wingetRemovalFailures [ $app ] = $true
2026-03-07 20:28:48 +01:00
}
}
}
2026-08-12 15:56:29 +02:00
$script:AppRemovalFailures += $wingetRemovalFailures . Count
2026-08-24 20:34:50 +02:00
return ( $script:AppRemovalFailures -eq $failuresBefore )
2026-06-22 22:13:01 +02:00
}
<#
. SYNOPSIS
2026-07-14 23:06:40 +03:00
Uninstalls an app via WinGet and/or schedules its removal.
2026-06-22 22:13:01 +02:00
.PARAMETER app
The WinGet package ID to uninstall (e.g. 'Microsoft.BingNews').
2026-08-09 01:24:27 +02:00
.PARAMETER TimeoutSeconds
Maximum time to allow the foreground WinGet uninstall to run. Defaults
to 120 seconds.
2026-08-24 20:34:50 +02:00
2026-10-12 23:53:08 +02:00
.PARAMETER SchedulingFailed
Optional reference indicating that required RunOnce scheduling was incomplete.
2026-08-24 20:34:50 +02:00
. OUTPUTS
System.Boolean. $true unless the winget invocation threw a terminating error
or any required RunOnce scheduling failed; otherwise $false.
2026-06-22 22:13:01 +02:00
#>
function Remove-WinGetApp {
2026-08-09 01:24:27 +02:00
param (
[ string ] $app ,
2026-10-12 23:53:08 +02:00
[ int ] $TimeoutSeconds = 120 ,
[ ref ] $SchedulingFailed
2026-08-09 01:24:27 +02:00
)
2026-06-22 22:13:01 +02:00
2026-10-12 23:53:08 +02:00
if ( $null -ne $SchedulingFailed ) { $SchedulingFailed . Value = $false }
2026-06-22 22:13:01 +02:00
if ( -not $script:WingetInstalled ) {
2026-08-12 15:56:29 +02:00
Write-Error "WinGet is either not installed or is outdated; $app could not be removed"
return $false
2026-06-22 22:13:01 +02:00
}
2026-08-24 20:34:50 +02:00
$uninstallCommandSucceeded = $true
$exitCode = $null
2026-10-12 23:53:08 +02:00
$userScopeBlocked = $false
$scheduleSucceeded = $true
$runOnceTarget = $null
2026-08-09 01:24:27 +02:00
try {
2026-08-24 20:34:50 +02:00
$uninstallResult = Invoke-NonBlocking -ScriptBlock {
2026-08-09 01:24:27 +02:00
param ( $appId )
2026-08-24 20:34:50 +02:00
$output = @ (& winget uninstall - -accept-source-agreements - -disable-interactivity - -id $appId 2 >& 1 )
return [ PSCustomObject ] @ {
ExitCode = $LASTEXITCODE
Output = $output
}
2026-08-09 01:24:27 +02:00
} -ArgumentList $app -TimeoutSeconds $TimeoutSeconds
2026-08-24 20:34:50 +02:00
Write-WinGetUninstallOutput -Output $ ( if ( $uninstallResult ) { $uninstallResult . Output } else { $null })
$exitCode = if ( $uninstallResult ) { $uninstallResult . ExitCode } else { 'unknown' }
Write-Verbose "WinGet uninstall for $app returned exit code $exitCode ."
2026-10-12 23:53:08 +02:00
# WinGet reports APPINSTALLER_CLI_ERROR_ADMIN_CONTEXT_ACTION_PROHIBITED (0x8A15007D).
# Keep the English message check as a fallback for clients that don't return the specific code.
$userScopeBlocked = ([ string ] $exitCode -eq '-1978335107' ) -or ([ string ] $exitCode -match '^0x0?8A15007D$' )
if ( -not $userScopeBlocked ) {
$userScopeBlocked = @ ( $uninstallResult . Output | Where-Object {
$null -ne $_ -and $_ . ToString () -match 'package installed for user scope cannot be uninstalled when running with administrator privileges'
}). Count -gt 0
}
if ( $userScopeBlocked ) {
$scheduleSucceeded = $false
$runOnceTarget = Get-RunOnceWingetTarget
$targetUserName = $runOnceTarget . UserName
$scheduleSucceeded = Set-RunOnceWingetTask -appId $app -Target $runOnceTarget
if ( $scheduleSucceeded ) {
if ( -not $script:WingetDeferredRemovals ) { $script:WingetDeferredRemovals = @ {} }
$script:WingetDeferredRemovals [ $app ] = $targetUserName
if ( $runOnceTarget . AllUsers ) {
Write-Host ( Get-Translation -Key 'WingetAllUsersUninstallDeferred' -FormatArgs @ ( $app )) -ForegroundColor Yellow
}
else {
Write-Host ( Get-Translation -Key 'WingetUserScopeUninstallDeferred' -FormatArgs @ ( $app , $targetUserName )) -ForegroundColor Yellow
}
}
}
2026-08-09 01:24:27 +02:00
}
catch {
2026-08-24 20:34:50 +02:00
$uninstallCommandSucceeded = $false
2026-08-09 01:24:27 +02:00
if ( $_ . Exception . Message -like 'Operation timed out after *' ) {
2026-10-17 00:46:35 +02:00
Write-Error "WinGet uninstall for $app did not complete within $TimeoutSeconds seconds: $_ "
2026-08-09 01:24:27 +02:00
}
else {
2026-08-24 20:34:50 +02:00
Write-Verbose "WinGet uninstall for $app failed: $_ "
2026-08-09 01:24:27 +02:00
}
}
2026-07-14 23:06:40 +03:00
2026-10-12 23:53:08 +02:00
if ( -not $userScopeBlocked -and
( $script:Params . ContainsKey ( 'User' ) -or $script:Params . ContainsKey ( 'Sysprep' ))) {
$runOnceTarget = Get-RunOnceWingetTarget
$targetDescription = if ( $runOnceTarget . AllUsers ) { 'all users' }
elseif ( $script:Params . ContainsKey ( 'Sysprep' ) -and -not $script:Params . ContainsKey ( 'AppRemovalTarget' )) { 'new users' }
else { "user $( $runOnceTarget . UserName ) " }
Write-Host "Adding RunOnce uninstall for $app for $targetDescription ..."
$scheduleSucceeded = Set-RunOnceWingetTask -appId $app -Target $runOnceTarget
2026-10-27 23:08:46 +01:00
if ( $scheduleSucceeded ) {
if ( -not $script:WingetDeferredRemovals ) { $script:WingetDeferredRemovals = @ {} }
$script:WingetDeferredRemovals [ $app ] = $runOnceTarget . UserName
}
2026-06-22 22:13:01 +02:00
}
2026-08-12 15:56:29 +02:00
2026-10-12 23:53:08 +02:00
if ( $null -ne $SchedulingFailed ) { $SchedulingFailed . Value = -not $scheduleSucceeded }
2026-08-24 20:34:50 +02:00
return ( $uninstallCommandSucceeded -and $scheduleSucceeded )
}
<#
. SYNOPSIS
Writes captured WinGet uninstall output to the verbose stream.
. OUTPUTS
None.
#>
function Write-WinGetUninstallOutput {
param (
[ object[] ] $Output
)
foreach ( $line in @ ( $Output )) {
if ( $null -eq $line ) { continue }
$lineText = if ( $line -is [ System.Management.Automation.ErrorRecord ]) { $line . Exception . Message } else { $line . ToString () }
if ([ string ]:: IsNullOrWhiteSpace ( $lineText )) { continue }
Write-Verbose $lineText
}
2026-06-22 22:13:01 +02:00
}
<#
. SYNOPSIS
Removes an app via Remove-AppxPackage / Remove-ProvisionedAppxPackage.
.PARAMETER app
The package identifier to remove (e.g. 'Clipchamp.Clipchamp').
.PARAMETER targetUser
Target scope: "AllUsers", "CurrentUser", or a specific username.
#>
function Remove-AppxApp {
param ([ string ] $app , [ string ] $targetUser )
$appPattern = '*' + $app + '*'
2026-10-18 23:07:42 +02:00
$isWindows10 = $script:WinVersion -ge 10240 -and $script:WinVersion -lt 22000
2026-06-22 22:13:01 +02:00
try {
2026-08-12 15:56:29 +02:00
$removalResult = Invoke-NonBlocking -ScriptBlock {
2026-10-18 23:07:42 +02:00
param ( $pattern , $target , $isWindows10 )
2026-08-12 15:56:29 +02:00
$removalErrors = @ ()
2026-10-18 23:07:42 +02:00
$ignoredRemovalMessages = [ System.Collections.Generic.List[string] ]:: new ()
$verificationWarnings = [ System.Collections.Generic.List[string] ]:: new ()
2026-08-12 15:56:29 +02:00
$getPackageParams = @ { Name = $pattern ; ErrorAction = 'Continue' ; ErrorVariable = '+removalErrors' }
2026-10-18 23:07:42 +02:00
$removePackageParams = @ { ErrorAction = 'Stop' }
# Windows 10 can report file-not-found after successfully removing an Appx package.
# Suppress it only after confirming the exact package is absent in the same scope.
function Test-IgnorableAppxRemovalError {
param ( $RemovalError , [ string ] $PackageName , [ switch ] $Provisioned )
if ( -not ( $isWindows10 -and ( $RemovalError . Exception . HResult -eq -2147024894 -or
$RemovalError . ToString () -match '\b0x80070002\b' ))) {
return $false
}
try {
if ( $Provisioned ) {
$remainingPackages = @ ( Get-AppxProvisionedPackage -Online -ErrorAction Stop |
Where-Object { $_ . PackageName -eq $PackageName })
}
else {
$verificationParams = $getPackageParams . Clone ()
$verificationParams . Remove ( 'ErrorVariable' )
$verificationParams . ErrorAction = 'Stop'
$remainingPackages = @ ( Get-AppxPackage @verificationParams |
Where-Object { $_ . PackageFullName -eq $PackageName })
}
return ( $remainingPackages . Count -eq 0 )
}
catch {
# An unsuccessful query cannot confirm removal; preserve the original error.
$verificationWarnings . Add ( "Unable to verify removal of $PackageName (target: $target , provisioned: $Provisioned ): $_ " )
return $false
}
}
2026-08-12 15:56:29 +02:00
switch ( $target ) {
'AllUsers' {
$getPackageParams . AllUsers = $true
$removePackageParams . AllUsers = $true
}
'CurrentUser' { }
default {
$userAccount = New-Object System . Security . Principal . NTAccount ( $target )
2026-06-22 22:13:01 +02:00
$userSid = $userAccount . Translate ([ System.Security.Principal.SecurityIdentifier ]). Value
2026-08-12 15:56:29 +02:00
$getPackageParams . User = $userSid
$removePackageParams . User = $userSid
}
2026-06-22 22:13:01 +02:00
}
2026-08-12 15:56:29 +02:00
foreach ( $package in @ ( Get-AppxPackage @getPackageParams )) {
$removePackageParams . Package = $package . PackageFullName
2026-10-18 23:07:42 +02:00
try {
$null = Remove-AppxPackage @removePackageParams
}
catch {
if ( Test-IgnorableAppxRemovalError $_ -PackageName $package . PackageFullName ) {
$ignoredRemovalMessages . Add ( "Windows 10 Appx removal reported error 0x80070002 for $( $package . PackageFullName ) , but the removal succeeded." )
}
else {
Write-Error -ErrorRecord $_ -ErrorAction Continue -ErrorVariable + removalErrors
}
}
2026-08-12 15:56:29 +02:00
}
if ( $target -eq 'AllUsers' ) {
$provisionedPackages = @ ( Get-AppxProvisionedPackage -Online -ErrorAction Continue -ErrorVariable + removalErrors | Where-Object { $_ . PackageName -like $pattern })
foreach ( $package in $provisionedPackages ) {
2026-10-18 23:07:42 +02:00
try {
$null = Remove-ProvisionedAppxPackage -Online -AllUsers -PackageName $package . PackageName -ErrorAction Stop
}
catch {
if ( Test-IgnorableAppxRemovalError $_ -PackageName $package . PackageName -Provisioned ) {
$ignoredRemovalMessages . Add ( "Windows 10 Appx removal reported error 0x80070002 for $( $package . PackageName ) , but the removal succeeded." )
}
else {
Write-Error -ErrorRecord $_ -ErrorAction Continue -ErrorVariable + removalErrors
}
}
2026-08-12 15:56:29 +02:00
}
}
2026-10-18 23:07:42 +02:00
return [ PSCustomObject ] @ {
Success = ( $removalErrors . Count -eq 0 )
IgnoredRemovalMessages = $ignoredRemovalMessages . ToArray ()
VerificationWarnings = $verificationWarnings . ToArray ()
}
} -ArgumentList @ ( $appPattern , $targetUser , $isWindows10 )
2026-06-22 22:13:01 +02:00
}
catch {
2026-08-12 15:56:29 +02:00
Write-Error "Unable to remove $app via Appx: $_ "
return $false
2026-06-22 22:13:01 +02:00
}
2026-10-18 23:07:42 +02:00
# Write in the caller's runspace so the active transcript captures these messages in GUI mode too.
foreach ( $message in @ ( $removalResult . IgnoredRemovalMessages )) {
if ( $message ) { Write-Host $message }
}
foreach ( $message in @ ( $removalResult . VerificationWarnings )) {
if ( $message ) { Write-Warning $message }
}
2026-08-12 15:56:29 +02:00
return [ bool ]( $removalResult -and $removalResult . Success )
2026-06-22 22:13:01 +02:00
}
<#
. SYNOPSIS
Returns the removal method for an app identifier.
. DESCRIPTION
Parses Apps.json once (cached in script scope) to build a lookup of
AppId -> RemovalMethod. Returns 'WinGet' if the app should be removed
via winget, or 'Appx' if via Remove-AppxPackage. Defaults to 'Appx'
for unknown IDs.
.PARAMETER appId
The package identifier (e.g. 'Clipchamp.Clipchamp').
#>
function Get-AppRemovalMethod {
param ([ string ] $appId )
if ( -not $script:AppRemovalMethodCache ) {
$script:AppRemovalMethodCache = @ {}
try {
if ( Test-Path $script:AppsListFilePath ) {
2026-10-21 22:54:20 +08:00
$appsJson = Get-Content -Path $script:AppsListFilePath -Raw -Encoding UTF8 | ConvertFrom-Json
2026-06-22 22:13:01 +02:00
foreach ( $appData in $appsJson . Apps ) {
$rawMethod = $appData . RemovalMethod
$method = if ( $rawMethod -and $rawMethod -eq 'WinGet' ) { 'WinGet' } else { 'Appx' }
2026-07-19 22:06:07 +02:00
foreach ( $id in @ ( $appData . AppId )) {
if ( $id -isnot [ string ]) { continue }
$normalizedId = $id . Trim ()
if ( -not [ string ]:: IsNullOrWhiteSpace ( $normalizedId )) {
$script:AppRemovalMethodCache [ $normalizedId ] = $method
}
2026-06-22 22:13:01 +02:00
}
}
}
}
catch {
Write-Warning "Failed to load app removal methods from ' $script:AppsListFilePath '. Defaulting unknown apps to Appx. Error: $_ "
}
}
if ( $script:AppRemovalMethodCache . ContainsKey ( $appId )) {
return $script:AppRemovalMethodCache [ $appId ]
}
return 'Appx'
}
<#
. SYNOPSIS
Prompts the user to forcefully remove Microsoft Edge when winget cannot uninstall it.
. DESCRIPTION
Only invoked after it has been confirmed that Edge is still present
following all winget uninstall attempts. In GUI mode, displays a
warning message box; in CLI mode, prompts via Read-Host. On
confirmation, performs a force-remove of the Edge package.
2026-08-24 20:34:50 +02:00
. OUTPUTS
System.Boolean. $true when Edge is forcefully removed; otherwise $false.
2026-06-22 22:13:01 +02:00
#>
function Request-EdgeForceRemove {
if ( $script:GuiWindow ) {
2026-09-10 21:18:43 +05:30
$result = Show-MessageBox -Message ( Get-Translation -Key 'ForceRemoveEdgeMessage' ) -Title ( Get-Translation -Key 'ForceRemoveEdgeTitle' ) -Button 'YesNo' -Icon 'Warning'
2026-06-22 22:13:01 +02:00
if ( $result -eq 'Yes' ) {
Write-Host ""
2026-08-24 20:34:50 +02:00
return ( Invoke-ForceRemoveEdge )
2026-06-22 22:13:01 +02:00
}
}
elseif ( $ ( Read-Host -Prompt "Would you like to forcefully uninstall Microsoft Edge? NOT RECOMMENDED! (y/n)" ) -eq 'y' ) {
Write-Host ""
2026-08-24 20:34:50 +02:00
return ( Invoke-ForceRemoveEdge )
2026-06-22 22:13:01 +02:00
}
2026-08-24 20:34:50 +02:00
return $false
2026-06-22 22:13:01 +02:00
}
<#
. SYNOPSIS
2026-10-12 23:53:08 +02:00
Resolves the user scope for deferred WinGet uninstall tasks.
2026-06-22 22:13:01 +02:00
. DESCRIPTION
2026-10-12 23:53:08 +02:00
Uses the selected app-removal target and launch parameters to determine
whether tasks apply to all users or a single user, including the Default profile.
. OUTPUTS
System.Management.Automation.PSCustomObject. AllUsers (Boolean) indicates
whether to schedule for all users. UserName (String) identifies the target
account or Default profile when AllUsers is false.
#>
function Get-RunOnceWingetTarget {
$appRemovalTarget = Get-TargetUserForAppRemoval
$hasExplicitAppRemovalTarget = $script:Params . ContainsKey ( 'AppRemovalTarget' )
$allUsers = $appRemovalTarget -eq 'AllUsers' -and (
$hasExplicitAppRemovalTarget -or
-not ( $script:Params . ContainsKey ( 'User' ) -or $script:Params . ContainsKey ( 'Sysprep' ))
)
$userName = if ( $allUsers ) {
Get-UserName
}
elseif ( $hasExplicitAppRemovalTarget ) {
if ( $appRemovalTarget -ieq 'CurrentUser' -or $appRemovalTarget -ieq 'AllUsers' ) {
Get-UserName
}
else {
$appRemovalTarget
}
}
elseif ( $script:Params . ContainsKey ( 'Sysprep' )) {
'Default'
}
else {
Get-UserName
}
return [ PSCustomObject ] @ {
AllUsers = [ bool ] $allUsers
UserName = [ string ] $userName
}
}
<#
. SYNOPSIS
Returns the profile targets for deferred AllUsers WinGet uninstall tasks.
. DESCRIPTION
Lists resolvable accounts with non-special profiles containing NTUSER.DAT.
Includes Default so the task also applies to profiles created later.
Profiles whose SIDs cannot be resolved are skipped with a warning and mark
the result incomplete.
. OUTPUTS
System.Management.Automation.PSCustomObject. UserNames contains account names
and Default. Success is false if enumeration or any SID translation fails.
#>
function Get-RunOnceWingetTargetUserNames {
$targetUsers = New-Object 'System.Collections.Generic.List[string]'
$seenSids = @ {}
$allSucceeded = $true
try {
foreach ( $userProfile in @ ( Get-CimInstance -ClassName Win32_UserProfile -ErrorAction Stop )) {
if ( $userProfile . Special -or [ string ]:: IsNullOrWhiteSpace ([ string ] $userProfile . SID ) -or
[ string ]:: IsNullOrWhiteSpace ([ string ] $userProfile . LocalPath )) {
continue
}
$hivePath = Join-Path $userProfile . LocalPath 'NTUSER.DAT'
if ( -not ( Test-Path -LiteralPath $hivePath )) { continue }
$sid = [ string ] $userProfile . SID
if ( $seenSids . ContainsKey ( $sid )) { continue }
try {
$accountName = ([ System.Security.Principal.SecurityIdentifier ] $sid ). Translate (
[ System.Security.Principal.NTAccount ]
). Value
}
catch {
$allSucceeded = $false
Write-Warning "The deferred AllUsers WinGet uninstall may be incomplete: unable to resolve account name for profile SID ' $sid '. This profile will not be scheduled. $_ "
continue
}
$seenSids [ $sid ] = $true
$targetUsers . Add ( $accountName )
}
}
catch {
Write-Error "Unable to enumerate user profiles for deferred WinGet uninstall: $_ "
return [ PSCustomObject ] @ { UserNames = @ (); Success = $false }
}
# RunOnce values in the Default profile are copied into profiles created later.
$targetUsers . Add ( 'Default' )
return [ PSCustomObject ] @ { UserNames = @ ( $targetUsers ); Success = $allSucceeded }
}
<#
. SYNOPSIS
Dynamically sets RunOnce registry keys to schedule a winget uninstall.
. DESCRIPTION
Writes through Invoke-WithTargetUserHive,
2026-06-22 22:13:01 +02:00
which handles hive loading and HKEY_USERS\Default → SID remapping.
Used instead of static .reg files to avoid file dependency for each WinGet app.
2026-10-27 23:08:46 +01:00
Invokes winget.exe directly with a quoted app ID, without a shell wrapper.
Escapes embedded quotes and trailing backslashes for native argument parsing,
and rejects commands exceeding RunOnce's 260-character limit.
2026-06-22 22:13:01 +02:00
.PARAMETER appId
The winget package ID to schedule for uninstall (e.g. 'XP9CXNGPPJ97XX').
2026-10-12 23:53:08 +02:00
.PARAMETER Target
Resolved RunOnce target from Get-RunOnceWingetTarget.
2026-06-22 22:13:01 +02:00
#>
function Set-RunOnceWingetTask {
2026-10-12 23:53:08 +02:00
param (
[ string ] $appId ,
[ PSCustomObject ] $Target
)
2026-06-22 22:13:01 +02:00
2026-10-12 23:53:08 +02:00
if ( $null -eq $Target ) { $Target = Get-RunOnceWingetTarget }
$allSucceeded = $true
$targetUserNames = if ( $Target . AllUsers ) {
$profileTargets = Get-RunOnceWingetTargetUserNames
$allSucceeded = $profileTargets . Success
@ ( $profileTargets . UserNames )
}
else {
@ ( $Target . UserName )
}
if ( $targetUserNames . Count -eq 0 ) { return $false }
2026-06-22 22:13:01 +02:00
# Sanitize appId for use in registry value names (backslashes are path separators)
$safeAppId = $appId . Replace ( '\' , '_' )
$taskName = "Uninstall_ $safeAppId "
2026-10-27 23:08:46 +01:00
# Preserve the ID as one native argument. No cmd.exe or PowerShell interprets its contents.
$escapedAppId = $appId -replace '(\\*)"' , '$1$1\"'
$escapedAppId = $escapedAppId -replace '(\\+)$' , '$1$1'
$wingetCommand = "winget.exe uninstall --accept-source-agreements --disable-interactivity --id `" $escapedAppId `" "
if ( $wingetCommand . Length -gt 260 ) {
Write-Error "Failed to schedule uninstall task for $( $appId ) : the RunOnce command exceeds 260 characters."
return $false
}
2026-06-22 22:13:01 +02:00
$operation = [ PSCustomObject ] @ {
KeyPath = 'HKEY_USERS\Default\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'
ValueName = $taskName
ValueType = 'String'
2026-10-27 23:08:46 +01:00
ValueData = $wingetCommand
2026-06-22 22:13:01 +02:00
OperationType = 'SetValue'
}
2026-10-12 23:53:08 +02:00
foreach ( $targetUserName in $targetUserNames ) {
try {
Invoke-WithTargetUserHive -TargetUserName $targetUserName -ScriptBlock {
param ( $op )
Invoke-RegistryOperation -Operation $op -RegFilePath '<dynamic>'
} -ArgumentObject $operation
}
catch {
Write-Error "Failed to schedule uninstall task for $( $appId ) for ' $targetUserName ': $_ "
$allSucceeded = $false
}
2026-06-22 22:13:01 +02:00
}
2026-10-12 23:53:08 +02:00
return $allSucceeded
2026-07-14 23:06:40 +03:00
}