Powershell "Add-Type" creates random folders in temporary folder

Hi,

why is “Add-Type” flooding my windows temp folder with empty folders? take a look at my sample script, it creates 5 empty folders inside the temp folder. (when running as admin)

# Loop to run the job 5 times
for ($i = 1; $i -le 5; $i++) {
    # Start a background job (script block)
    $job = Start-Job -ScriptBlock {
        # .Net methods for hiding/showing the console in the background (running in background job)
        Add-Type -Name Window -Namespace Console -MemberDefinition '
        [DllImport("Kernel32.dll")]
        public static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
        '

        function Show-Console {
            $consolePtr = [Console.Window]::GetConsoleWindow()
            [Console.Window]::ShowWindow($consolePtr, 4) # Show the console window
        }

        function Hide-Console {
            $consolePtr = [Console.Window]::GetConsoleWindow()
            [Console.Window]::ShowWindow($consolePtr, 0) # Hide the console window
        }

        # Hide the console window in the background job
        Hide-Console

        # Simulate some work
        Start-Sleep -Seconds 1

        # Show the console window again
        Show-Console
    }

    # wait for each job to complete before starting the next one
    Wait-Job -Job $job
    Receive-Job -Job $job

    # Clean up the background job after each iteration
    Remove-Job -Job $job

    # Pause between job executions
    Start-Sleep -Seconds 1
}

Write-Host "All jobs have been executed."

Hi, welcome to the forum :wave:

PowerShell on .NET Core does not create these folders as far as I can tell. This only occurs when running Windows PowerShell under .NET.

I found this explanation which describes how they’re created:

Although the temporary files get removed, it does leave a folder behind.

2 Likes

Thanks, now I finally know why it happens. So the only way is to create a function which checks for newly created empty folders inside the temp folder and delete them?

As far as I can tell from my testing the folders are left behind only when it’s run elevated. As a normal user they’re not left behind, although they do appear to be created in the same path (according to Process Monitor).

Rather than search for the folders, you could use the -PassThrough parameter with Add-Type. This will return an object representing the types that were added and you can get the folder name from either the Module property (replacing .dll) or the Assembly property (split on comma and get the first element).

RunspaceId                : 0a285962-6638-4a79-aa4f-59a95757c7bf
Module                    : iae05yjp.dll
Assembly                  : iae05yjp, Version=0.0.0.0, Culture=neutral,
                            PublicKeyToken=null
4 Likes

This is perfect, thank you.