# Save as WinSxSDeleteEmptyInFlightFolders.ps1
# Run with .\WinSxSDeleteEmptyInFlightFolders.ps1
# To See the all output in the console, run with .\WinSxSDeleteEmptyInFlightFolders.ps1 -Verbose
# Report issus with this script at: https://www.elevenforum.com/t/c-windows-winsxs-temp-inflight-deleting-empty-folders.33434/
# Version 0.5
param(
[switch]
$Verbose
)
function Invoke-WinSxSDeleteEmptyInFlightFolders {
begin {
#region Enable Privilege function
function Enable-Privilege {
param(
## The privilege to adjust. This set is taken from
## http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx
[ValidateSet(
"SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
"SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
"SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
"SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
"SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
"SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
"SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
"SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
"SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
"SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
"SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
$Privilege,
## The process on which to adjust the privilege. Defaults to the current process.
$ProcessId = $pid,
## Switch to disable the privilege, rather than enable it.
[Switch] $Disable
)
## Taken from P/Invoke.NET with minor adjustments.
$definition = @'
using System;
using System.Runtime.InteropServices;
public class AdjPriv
{
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
{
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = new IntPtr(processHandle);
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
if (!retVal) return false;
tp.Count = 1;
tp.Luid = 0;
tp.Attr = disable ? SE_PRIVILEGE_DISABLED : SE_PRIVILEGE_ENABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
if (!retVal) return false;
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
}
'@
$processHandle = (Get-Process -id $ProcessId).Handle
$typeexists = try { ([AdjPriv] -is [type]); $true } catch { $false }
if ( $typeexists -eq $false ) {
$type = Add-Type $definition -PassThru
}
$result = [AdjPriv]::EnablePrivilege($processHandle, $Privilege, $Disable)
if (-not $result) {
$errorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
throw "Failed to change privilege '$Privilege'. Error code: $errorCode."
}
}
#endregion Enable Privilege function
}
process {
try {
# Check for Admin rights
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
Write-Warning "Must be run with administrator credentials"
return
}
try {
# Add SeTakeOwnershipPrivilege and SeRestorePrivilege for this process
Enable-Privilege -Privilege SeTakeOwnershipPrivilege
Enable-Privilege -Privilege SeRestorePrivilege
}
catch {
Write-Error $_.Exception.Message
return
}
$totalDeletedFolderCount = 0
do {
# Find empty folders
$emptyFolders = Get-ChildItem -Path $env:windir\WinSxS\Temp\InFlight -Recurse -Directory | Where-Object { (Get-ChildItem -Path $_.FullName -Force).Count -eq 0 }
# If no empty folders are found, exit the loop
if ($emptyFolders.Count -eq 0) {
break
}
# Initialize a counter for deleted folders in THIS ITERATION
$deletedFolderCount = 0
$NTAccount_Administrators = [System.Security.Principal.NTAccount]"Administrators"
foreach ($emptyInFlightFolder In $emptyFolders) {
#region Change ownership of the root folder
try {
$acl = Get-Acl -Path $emptyInFlightFolder.FullName
$acl.SetOwner($NTAccount_Administrators)
Set-Acl -Path $emptyInFlightFolder.FullName -AclObject $acl
Write-Host "Changed owner on '$($emptyInFlightFolder.FullName)' to '$($NTAccount_Administrators)'..."
}
catch {
Write-Warning "Failed to change owner on folder $($emptyInFlightFolder.FullName). Error: $($_.Exception.Message)"
continue # Skip to the next folder if ownership change fails
}
#endregion
#region Add Administrators Full Control on the folder
try {
$acl = Get-Acl -Path $emptyInFlightFolder.FullName
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($NTAccount_Administrators, [System.Security.AccessControl.FileSystemRights]::FullControl, @("ObjectInherit", "ContainerInherit"), "None", "Allow")
$acl.AddAccessRule($accessRule)
Set-Acl -Path $emptyInFlightFolder.FullName -AclObject $acl
if ($Verbose) { Write-Host "[Folder] Added Administrators with full control on '$($emptyInFlightFolder.FullName)' to '$($NTAccount_Administrators)'..." -ForegroundColor Cyan }
}
catch {
Write-Warning "Failed to add full control permissions to folder $($emptyInFlightFolder.FullName). Error: $($_.Exception.Message)"
continue # Skip to the next folder if adding permissions fails
}
#endregion
# Attempt to remove the folder
try {
Remove-Item -Path "$($emptyInFlightFolder.FullName)" -Recurse -Force -Confirm:$false
$deletedFolderCount++ # Increment the counter if deletion is successful
if ($Verbose) { Write-Host "Successfully deleted folder: $($emptyInFlightFolder.FullName)" }
}
catch {
Write-Warning "Failed to delete folder $($emptyInFlightFolder.FullName). Error: $($_.Exception.Message)"
}
}
# Add the number of folders deleted in this iteration to the total
$totalDeletedFolderCount += $deletedFolderCount
} while ($true) # Infinite loop that breaks when no empty folders are found
if ($totalDeletedFolderCount -eq 0) {
Write-Host "No empty folders were found."
} else {
Write-Host "Total empty folders deleted across all iterations: $totalDeletedFolderCount" # Display total at the end
}
}
catch {
Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
throw $_
}
}
end {}
}
Invoke-Command -ScriptBlock { Invoke-WinSxSDeleteEmptyInFlightFolders }