C:\Windows\System32\config\systemprofile\AppData\Local Delete Empty tw-*.tmp Folders


Tester

Well-known member
Member
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:
1739645997480.webp

1739646239799.webp

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

More topics and scripts to delete Emtpy folder in the Windows Folder.

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
Don't install unnecessary programs and you won't have to clean. IMO.

1.webp
 

My Computer

System One

  • OS
    Microsoft Windows 11 Home
    Computer type
    PC/Desktop
    Manufacturer/Model
    MSI MS-7D98
    CPU
    Intel Core i5-13490F
    Motherboard
    MSI B760 GAMING PLUS WIFI
    Memory
    2 x 16 Patriot Memory (PDP Systems) PSD516G560081
    Graphics Card(s)
    GIGABYTE GeForce RTX 4070 WINDFORCE OC 12G (GV-N4070WF3OC-12GD)
    Sound Card
    Bluetooth Аудио
    Monitor(s) Displays
    INNOCN 15K1F
    Screen Resolution
    1920 x 1080
    Hard Drives
    WD_BLACK SN770 250GB
    KINGSTON SNV2S1000G (ELFK0S.6)
    PSU
    Thermaltake Toughpower GF3 1000W
    Case
    CG560 - DeepCool
    Cooling
    ID-COOLING SE-224-XTS / 2 x 140Mm Fan - rear and top; 3 x 120Mm - front
    Keyboard
    Corsair K70 RGB TKL
    Mouse
    Corsair KATAR PRO XT
    Internet Speed
    100 Mbps
    Browser
    Firefox
    Antivirus
    Microsoft Defender Antivirus
    Other Info
    https://www.userbenchmark.com/UserRun/66553205
@RickC has a TenForum thread which advises they're junk folders by created by a pair of Windows provisioning tasks.
 
Last edited:

My Computer

System One

  • OS
    Windows 7
In the Local Folder it self, are also some other files from some programs.
Like malwarebytes with some logs, and Visual Studio items, perhaps on other systems also other applications. But thats not really an issue. This topic is related to cleaning up emtpy folders like: tw-1a64-13e4-122a1e.tmp
 

My Computer

System One

  • OS
    Windows 11
    Computer type
    PC/Desktop
Back
Top Bottom