- Local time
- 8:44 AM
- Posts
- 248
- OS
- Windows 11
This is the last place where there are leftovers empty folders in the Windows Folder.
This one happens after Microsoft Provisioning has run.
Read here more, as those folders can be deleted: Redirecting
1600+ empty folders on one system dating back to early last year:


On a other system... Run with the -Verbose command.

More topics and scripts to delete Emtpy folder in the Windows Folder.
www.elevenforum.com
www.elevenforum.com
I appreciate the feedback!
This one happens after Microsoft Provisioning has run.
Read here more, as those folders can be deleted: Redirecting
1600+ empty folders on one system dating back to early last year:


On a other system... Run with the -Verbose command.

More topics and scripts to delete Emtpy folder in the Windows Folder.
C:\Windows\WinSxS\Temp\InFlight\ Deleting Empty Folders
Hi, I am testing and making a powershell script to delete empty folders in C:\Windows\WinSxS\Temp\InFlight\ To my understanding when updates or other windows operations occur, files in use might be placed there, and upon a restart they will be cleared. On a lot of systems, i have thousands...

C:\Windows\assembly\NativeImages_v*\Temp Delete Emtpy Folders
After searching empty folders that are not deleted by windows, this is one more locations where a lot of empty folders are created and not used anymore. So based on this topic C:\Windows\WinSxS\Temp\InFlight\ Deleting Empty Folders I created a powershell script to also delete the Empty Folders...

I appreciate the feedback!
Powershell:
# Save as DeleteSystemProfileProvisioningEmptyTmpFolders.ps1
# Run with .\DeleteSystemProfileProvisioningEmptyTmpFolders.ps1
# To See the all output in the console, run with .\DeleteSystemProfileProvisioningEmptyTmpFolders.ps1 -Verbose
# Version 0.1
param(
[switch]
$Verbose
)
function Invoke-DeleteSystemProfileProvisioningEmptyTmpFolders {
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
}
# Set the path to the folder
$folderPath = "$env:windir\System32\config\systemprofile\AppData\Local\"
$totalDeletedFolderCount = 0
do {
# Find empty folders example: tw-1a64-13e4-122a1e.tmp
$emptyFolders = Get-ChildItem -Path $folderPath -Recurse -Directory |
Where-Object {
$folder = $_.FullName
$_.Name -Like "tw-*" -and $_.Name -Like "*.tmp" -and (Get-ChildItem -Path $folder -Force | Measure-Object).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 ($emptySystemProfileProvisioningFolder In $emptyFolders) {
#region Change ownership of the root folder
try {
$acl = Get-Acl -Path $emptySystemProfileProvisioningFolder.FullName
$acl.SetOwner($NTAccount_Administrators)
Set-Acl -Path $emptySystemProfileProvisioningFolder.FullName -AclObject $acl
if ($Verbose) { Write-Host "Changed owner on '$($emptySystemProfileProvisioningFolder.FullName)' to '$($NTAccount_Administrators)'..." }
}
catch {
Write-Warning "Failed to change owner on folder $($emptySystemProfileProvisioningFolder.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 $emptySystemProfileProvisioningFolder.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 $emptySystemProfileProvisioningFolder.FullName -AclObject $acl
if ($Verbose) { Write-Host "[Folder] Added Administrators with full control on '$($emptySystemProfileProvisioningFolder.FullName)' to '$($NTAccount_Administrators)'..." -ForegroundColor Cyan }
}
catch {
Write-Warning "Failed to add full control permissions to folder $($emptySystemProfileProvisioningFolder.FullName). Error: $($_.Exception.Message)"
continue # Skip to the next folder if adding permissions fails
}
#endregion
# Attempt to remove the folder
try {
Remove-Item -Path "$($emptySystemProfileProvisioningFolder.FullName)" -Recurse -Force -Confirm:$false
$deletedFolderCount++ # Increment the counter if deletion is successful
if ($Verbose) { Write-Host "Successfully deleted folder: $($emptySystemProfileProvisioningFolder.FullName)" }
}
catch {
Write-Warning "Failed to delete folder $($emptySystemProfileProvisioningFolder.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, starting with ""tw-"" and ending with "".tmp""."
} 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-DeleteSystemProfileProvisioningEmptyTmpFolders }
Last edited:
My Computer
System One
-
- OS
- Windows 11
- Computer type
- PC/Desktop