Important Notice: On February 29th, this community was put into read-only mode. All existing posts will remain but customers are unable to add new posts or comment on existing. Please feel to join our Community Discord for any questions and discussions.

Powershell & Cleanmgr Exitcode Problem

Hi there,

I created a Powershell script with help from some Forums to delete an Windows.old Directory after Inplace Update.
But I get no Exit/Error Code from the Script because of Cleanmgr.

What my Script looks like:

if (Test-Path $env:SYSTEMDRIVE\Windows.old) {
# Add RegValue StateFlags1221
$regpath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Previous Installations'
New-ItemProperty -Path $regpath -Name 'StateFlags1221' -PropertyType DWORD -Value 2 -Force
# Start CleanUp
Start-Process cleanmgr `
-ArgumentList "/sagerun:1221" `
-Wait `
-NoNewWindow `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue
Exit 0

Cleanmgr runs and ended without that Powershell recognizes it. So the Script always ended with the Timeout from PDQ Deploy.
How can I change that?



Date Votes
  • I did it by myself.

    I created a Package that creates a Task (with schtasks), then it started the Task, and deleted it after.

    With that I get my succesfull Message.

    If anyone is Interested in that, I can post the Package.

  • Hi, 
    can you post the package,please?

  • Hi,

    no Problem. We copy the Inplace File to the C drive (\install\win), so in the first Step, we delete that Folder after the Update (All of that are normal commands):

    IF EXIST "C:\install\win" (
    rd c:\install\win10 /s /q

    Then add the needed RegKey (command):

    reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Previous Installations" /v StateFlags1221 /t REG_DWORD /d 2 /f

    Then create the Task (command):

    schtasks /create /tn "CleanUp" /RU SYSTEM /sc weekly /D MO /st 10:00 /sd 01/01/2022 /tr "cleanmgr.exe /sagerun:1221"

    After that, we create a Sleep of 3 seconds and then

    Start the Task (command):

    schtasks /run /I /tn "CleanUp"

    another Sleep of 10 seconds and then

    delete the Task (command):

    schtasks /delete /tn "CleanUp" /f


    Thats it. The shedule is deleted (not needed anymore) and the Task is running in the background. Depends on the Hardware, after 10-20min the Folder is gone. And you will get the success Code in PDQ.