Updated Windows Cleanup and Windows Update Reset

Discussion in 'Scripting' started by GodHand, Oct 1, 2018.

  1. GodHand

    GodHand MDL Senior Member

    Jul 15, 2016
    378
    410
    10
    #1 GodHand, Oct 1, 2018
    Last edited: Oct 3, 2018
    Windows Clean-up

    Code:
    Function Start-WindowsCleanup
    {
        <#
       .SYNOPSIS
           Clean-up temporary files and folders and reclaim disk space.
       
       .DESCRIPTION
           This functions cleans-up temporary Windows files, folders and directories.
           This function runs the Windows Disk Clean-up Manager by enabling all of its available clean-up options within the registry and then running the CleanMgr.exe as a .NET process.
           It enables all options by adding the StateFlags registry property name to the VolumeCache registry keys.
           These options are then disabled, after CleanMgr.exe has run, to ensure no other programs can utilize its features without permission.
       
       .PARAMETER StateFlags
           An optional numerical value for the StateFlags registry property name.
           This is not mandatory and simply allows one to change the numerical value of the StateFlags property name to any integer between 1-9999.
       
       .PARAMETER ComponentStore
           Additionally cleans up the WinSxS Component Store, with an option to reset the OS base.
       
       .PARAMETER WinSxS
           A description of the WinSxS parameter.
       
       .EXAMPLE
           PS C:\> Start-WindowsCleanup
           PS C:\> Start-WindowsCleanup -StateFlags 1234
           PS C:\> Start-WindowsCleanup -ComponentStore
    #>
       
       [CmdletBinding(ConfirmImpact = 'High',
                      SupportsShouldProcess = $true)]
       Param
       (
           [Parameter(Mandatory = $false,
                      Position = 0,
                      HelpMessage = 'An optional numerical value for the StateFlags registry property name.')]
           [ValidateRange(1, 9999)]
           [int]$StateFlags = 1,
           [Parameter(Position = 1,
                      HelpMessage = 'Additionally cleans up the WinSxS Component Store, with an option to reset the OS base.')]
           [switch]$ComponentStore
       )
       
       Begin
       {
           $StateFlagsName = "StateFlags{0:D4}" -f $StateFlags
           $Report = "Start-WindowsCleanup_" + $(Get-Date -Format "MM-dd-yyyy")
           Start-Transcript -Path "$Env:SystemRoot\Temp\$Report.log"
           $ErrorMessage = $_.ExceptionMessage
           Function Clear-Container
           {
               [CmdletBinding()]
               Param
               (
                   [string]$Folder,
                   [switch]$Remove
               )
               If ($Remove) { Remove-Item -Path $($Folder) -Recurse -Force -Verbose -ErrorAction SilentlyContinue }
               Else { Get-ChildItem -Path $($Folder) -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -Verbose -Erroraction SilentlyContinue }
           }
       }
       Process
       {
           If ($PSCmdlet.ShouldProcess("$Env:COMPUTERNAME, all distribution, logging and temporary content will be lost."))
           {
               $PreClean = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object DriveType -EQ 3 | Select-Object `
                                                                                                                       @{ Name = "Drive"; Expression = { ($_.DeviceID) } },
                                                                                                                       @{ Name = "Size (GB)"; Expression = { "{0:N1}" -f ($_.Size / 1GB) } },
                                                                                                                       @{ Name = "FreeSpace (GB)"; Expression = { "{0:N1}" -f ($_.Freespace / 1GB) } },
                                                                                                                       @{ Name = "PercentFree"; Expression = { "{0:P1}" -f ($_.FreeSpace / $_.Size) } } |
               Format-Table -AutoSize | Out-String
               Write-Warning "Cleaning-up Temporary, Distribution and Logging Folders. This may take a few minutes depending on their sizes. Please be patient."
               Start-Sleep 5
               Write-Output ''
               Get-Service -Name wuauserv -ErrorAction SilentlyContinue | Stop-Service -Verbose
               Start-Sleep 3
               Clear-Container -Folder "$Env:TEMP\*"
               Clear-Container -Folder "$Env:SystemRoot\Temp\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Temp\*"
               Clear-Container -Folder "$Env:SystemRoot\SoftwareDistribution\Download\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Windows\Temporary Internet Files\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatCache\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatUaCache\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Windows\IEDownloadHistory\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Windows\INetCache\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Windows\INetCookies\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Terminal Server Client\Cache\*"
               Clear-Container -Folder "C:\Users\*\AppData\Local\Microsoft\Windows\WER\*"
               Clear-Container -Folder "$Env:ProgramData\Microsoft\Windows\WER\*"
               Clear-Container -Folder "$Env:SystemRoot\Logs\WindowsUpdate\*"
               Clear-Container -Folder "$Env:SystemDrive\swtools\*"
               Clear-Container -Folder "$Env:SystemDrive\swsetup\*"
               Clear-Container -Folder "$Env:SystemRoot\drivers\*"
               Clear-Container -Folder "$Env:SystemDrive\Users\Administrator\Downloads\*"
               Clear-Container -Folder "$Env:SystemRoot\minidump\*"
               Clear-Container -Folder "$Env:SystemRoot\Prefetch\*"
               Clear-Container -Folder "$Env:SystemRoot\Logs\CBS\*.log" -Remove
               Clear-Container -Folder "$Env:SystemRoot\Logs\DISM\*.log*" -Remove
               Clear-Container -Folder "$Env:SystemRoot\memory.dmp" -Remove
               Clear-Container -Folder "$Env:HOMEDRIVE\inetpub\logs\LogFiles\*"
               Clear-Container -Folder "$Env:HOMEDRIVE\PerfLogs\*"
               Clear-Container -Folder "$Env:HOMEDRIVE\Config.Msi" -Remove
               Clear-Container -Folder "$Env:HOMEDRIVE\Intel\*"
               If (Test-Path -Path 'C:\$Recycle.Bin') { Remove-Item -LiteralPath 'C:\$Recycle.Bin' -Recurse -Force -Confirm:$false -Verbose -ErrorAction SilentlyContinue }
               If ($PSVersionTable.PSVersion.Major -le 4)
               {
                   $RecycleBin = (New-Object -ComObject Shell.Application).NameSpace(0xA)
                   $RecycleBin.Items() | ForEach-Object -Process { Remove-Item -LiteralPath $_.Path -Recurse -Force -Confirm:$false -Verbose -ErrorAction SilentlyContinue }
               }
               ElseIf ($PSVersionTable.PSVersion.Major -ge 5)
               {
                   Clear-RecycleBin -Force -Confirm:$false -Verbose -ErrorAction SilentlyContinue
               }
               $VolumeCache = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
               $VolumeCache.ForEach{
                   $EnableFlag = @{
                       Path         = $($_.PSPath)
                       Name         = $StateFlagsName
                       Value         = 2
                       PropertyType  = 'DWORD'
                       Force         = $true
                       ErrorAction   = 'SilentlyContinue'
                   }
                   [void](New-ItemProperty @EnableFlag)
               }
               $ObjProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
               $ObjProcess = New-Object System.Diagnostics.Process
               $ObjProcessInfo.FileName = "$($Env:SystemRoot)\System32\cleanmgr.exe"
               $ObjProcessInfo.Arguments = '/SAGERUN:{0}' -f $StateFlags.ToString()
               $ObjProcessInfo.CreateNoWindow = $true
               $ObjProcess.StartInfo = $ObjProcessInfo
               [void]$ObjProcess.Start()
               $GetProcess = Get-Process -Name cleanmgr -ErrorAction SilentlyContinue
               While ($($GetProcess.Refresh(); $GetProcess.ProcessName)) { Start-Sleep 0.5 }
               Get-Process -Name explorer | Stop-Process -Verbose
               Start-Sleep 5
               Get-Service -Name wuauserv -ErrorAction SilentlyContinue | Start-Service -Verbose
               Start-Sleep 3
               $VolumeCache = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
               $VolumeCache.ForEach{
                   $DisableFlag = @{
                       Path        = $($_.PSPath)
                       Name        = $StateFlagsName
                       ErrorAction  = 'SilentlyContinue'
                   }
                   Get-ItemProperty @DisableFlag | Remove-ItemProperty -Name $StateFlagsName -ErrorAction SilentlyContinue
               }
               If ($ComponentStore.IsPresent)
               {
                   $Wshell = New-Object -ComObject Wscript.Shell
                   $AskCleanup = $Wshell.Popup("Also reset the OS Base?", 15, "ResetBase", 4 + 32)
                   If ($AskCleanup -eq 6)
                   {
                       Write-Warning "An OS Base Reset can take quite a while. Please be patient and do not exit the clean-up process."
                       Start-Sleep 3
                       Try
                       {
                           If (!(Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration"))
                           {
                               [void](New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration" -Force -ErrorAction Stop)
                           }
                           Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration" -Name "DisableResetbase" -Value 0 -Type DWord
                           Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration" -Name "SupersededActions" -Value 1 -Type DWord
                           Start-Process -FilePath Dism -ArgumentList ("/English /Online /Cleanup-Image /StartComponentCleanup /ResetBase") -WindowStyle Hidden -Wait
                       }
                       Catch
                       {
                           Get-Process -Name Dism -ErrorAction SilentlyContinue | Stop-Process -Force -Confirm:$false
                           If ((Get-Service -Name Dism -ErrorAction SilentlyContinue).Status -eq "Running")
                           {
                               Get-Process -Name Dism -ErrorAction SilentlyContinue | ForEach-Object -Process { $_.Kill() }
                               Start-Sleep 5
                           }
                           Break
                       }
                   }
                   ElseIf ($AskCleanup -eq 7 -or $AskCleanup -eq -1)
                   {
                       Write-Host "Cleaning-up the component store. This could take a few minutes so please be patient." -ForegroundColor Cyan
                       Start-Sleep 3
                       Try
                       {
                           If (!(Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration"))
                           {
                               [void](New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration" -Force -ErrorAction Stop)
                           }
                           Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration" -Name "DisableResetbase" -Value 1 -Type DWord -ErrorAction Stop
                           Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Configuration" -Name "SupersededActions" -Value 0 -Type DWord -ErrorAction Stop
                           $NoResetBase = "/English /Online /Cleanup-Image /StartComponentCleanup /ResetBase"
                           Start-Process -FilePath Dism -ArgumentList ("/English /Online /Cleanup-Image /StartComponentCleanup") -WindowStyle Hidden -Wait
                       }
                       Catch
                       {
                           Get-Process -Name Dism -ErrorAction SilentlyContinue | Stop-Process -Force -Confirm:$false
                           If ((Get-Service -Name Dism -ErrorAction SilentlyContinue).Status -eq "Running")
                           {
                               Get-Process -Name Dism -ErrorAction SilentlyContinue | ForEach-Object -Process { $_.Kill() }
                               Start-Sleep 5
                           }
                           Break
                       }
                   }
               }
               $PostClean = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object DriveType -EQ 3 | Select-Object `
                                                                                                                        @{ Name = "Drive"; Expression = { ($_.DeviceID) } },
                                                                                                                        @{ Name = "Size (GB)"; Expression = { "{0:N1}" -f ($_.Size / 1GB) } },
                                                                                                                        @{ Name = "FreeSpace (GB)"; Expression = { "{0:N1}" -f ($_.Freespace / 1GB) } },
                                                                                                                        @{ Name = "PercentFree"; Expression = { "{0:P1}" -f ($_.FreeSpace / $_.Size) } } |
               Format-Table -AutoSize | Out-String
               Write-Output "`n`n`t`t`tBefore Clean-up:`n$PreClean"
               Write-Output "`t`t`tAfter Clean-up:`n$PostClean"
           }
       }
       End
       {
           Stop-Transcript
       }
    }
    

    You can add as many additional folders to clean by simply adding a Clear-Container -Folder "Path/To/Folder" command. The -Remove switch will remove the entire folder/directory, while omitting the -Remove switch will recursively remove all files, folders and directories within the root directory but will not remove the root directory itself.

    It sets the proper StateFlags on all available VolumeCaches in the registry and runs the advanced CleanManager exe as a .NET process to circumvent the annoying GUI that requires one to manually select each section to clean. It monitors the .NET processes until completion and then continues with the script.

    It also logs all actions processed to a transcript log that will be saved to 'C:\Temp', and will display both system space before the clean-up and after the clean-up.

    Windows Update Reset:

    Code:
    Function Reset-WindowsUpdate
    {
        <#
       .SYNOPSIS
           Cleans-up Windows Update distribution folders and resets all dependant services to their default state to mitigate any updaing problems.
    
       .DESCRIPTION
           Stops all Windows Update dependant services, then proceedes to clean all folders used by Windows Update.
           Regenerates the default file structure that Windows requires for proper WSUS service access and authentication.
           Returns all dependant files, security descriptors and permissions back to their default state.
           Resets the local network.
           Restarts all Windows Update dependant services, followed by reauthenticating the device with WSUS servers.
           Optionally, the system will display a progress bar countdown before restarting to futher clear any cache storage.
    
       .PARAMETER Restart
           An optional parameter that restarts the computer after the reset by entering an integer representing seconds.
           At the completion of the function, a progress bar will display a countdown before the system restarts.
    
       .EXAMPLE
           PS C:\> Reset-WindowsUpdate
           PS C:\> Reset-WindowsUpdate -Restart 15
    
       .NOTES
           It is recommended to restart the device after running this function to clear additional system cache reserves.
           Ensure anything of importance is saved or closed before the restart occurs.
    #>
        [CmdletBinding()]
        Param
        (
            [Parameter(Mandatory = $false,
                Position = 0,
                HelpMessage = 'Restart the computer after the reset by entering an integer representing seconds.')]
            [int]$Restart
        )
     
        Begin
        {
            $VerbosePreference = 'SilentlyContinue'
        }
        Process
        {
            Clear-Host
            Write-Host "Stopping the BITS, wuauserv, AppIDSvc and CryptSvc services..." -NoNewline -ForegroundColor Cyan
            (Get-Service -Name BITS, wuauserv, AppIDSvc, CryptSvc -ErrorAction SilentlyContinue) | Stop-Service
            If ((Get-Service -Name BITS -ErrorAction SilentlyContinue).Status -eq "Running") { Write-Warning "Failed to stop the BITS service."; Break }
            If ((Get-Service -Name wuauserv -ErrorAction SilentlyContinue).Status -eq "Running") { Write-Warning "Failed to stop the wuauserv service."; Break }
            If ((Get-Service -Name AppIDSvc -ErrorAction SilentlyContinue).Status -eq "Running") { Write-Warning "Failed to stop the AppIDSvc service."; Break }
            If ((Get-Service -Name CryptSvc -ErrorAction SilentlyContinue).Status -eq "Running") { Write-Warning "Failed to stop the CryptSvc service."; Break }
            Write-Host "[Complete]`n" -ForegroundColor Cyan
       
            Write-Host "Resetting update files and folders..." -NoNewline -ForegroundColor Cyan
            Get-Process -Name wuauclt -ErrorAction SilentlyContinue | Stop-Process
            Start-Process -FilePath IPCONFIG -ArgumentList ('/FLUSHDNS') -WindowStyle Hidden -Wait
            Remove-Item -Path "$Env:ALLUSERSPROFILE\Application Data\Microsoft\Network\Downloader\qmgr*.dat" -Force -Confirm:$false -ErrorAction SilentlyContinue
            Remove-Item -Path "$Env:ALLUSERSPROFILE\Microsoft\Network\Downloader\qmgr*.dat" -Force -Confirm:$false -ErrorAction SilentlyContinue
            Get-ChildItem -Path $Env:SystemRoot\Logs\WindowsUpdate\* -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue
            If (Test-Path -Path $Env:SystemRoot\WinSxS\pending.xml.bak) { Remove-Item -Path $Env:SystemRoot\WinSxS\pending.xml.bak -Force -Confirm:$false -ErrorAction SilentlyContinue }
            If (Test-Path -Path $Env:SystemRoot\SoftwareDistribution.bak) { Remove-Item -Path $Env:SystemRoot\SoftwareDistribution.bak -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue }
            If (Test-Path -Path $Env:SystemRoot\System32\Catroot2.bak) { Remove-Item -Path $Env:SystemRoot\System32\Catroot2.bak -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue }
            If (Test-Path -Path $Env:SystemRoot\WinSxS\pending.xml)
            {
                Start-Process -FilePath TAKEOWN -ArgumentList ("/F $Env:SystemRoot\WinSxS\pending.xml") -WindowStyle Hidden -Wait
                Start-Process -FilePath ATTRIB -ArgumentList ("-R -S -H /S /D $Env:SystemRoot\WinSxS\pending.xml") -WindowStyle Hidden -Wait
                Rename-Item -Path $Env:SystemRoot\WinSxS\pending.xml -NewName pending.xml.bak -ErrorAction SilentlyContinue
            }
            If (Test-Path -Path $Env:SystemRoot\SoftwareDistribution)
            {
                Start-Process -FilePath ATTRIB -ArgumentList ("-R -S -H /S /D $Env:SystemRoot\SoftwareDistribution") -WindowStyle Hidden -Wait
                Rename-Item -Path $Env:SystemRoot\SoftwareDistribution -NewName SoftwareDistribution.bak -ErrorAction SilentlyContinue
                If (Test-Path -Path $Env:SystemRoot\SoftwareDistribution) { Write-Warning "Failed to rename the SoftwareDistribution folder."; Continue }
            }
            If (Test-Path -Path $Env:SystemRoot\System32\Catroot2)
            {
                Start-Process -FilePath ATTRIB -ArgumentList ("-R -S -H /S /D $Env:SystemRoot\System32\Catroot2") -WindowStyle Hidden -Wait
                Rename-Item -Path $Env:SystemRoot\System32\Catroot2 -NewName Catroot2.bak -ErrorAction SilentlyContinue
            }
            If (Test-Path -Path $Env:SystemRoot\WindowsUpdate.log)
            {
                Start-Process -FilePath ATTRIB -ArgumentList ("-R -S -H /S /D $Env:SystemRoot\WindowsUpdate.log") -WindowStyle Hidden -Wait
                Rename-Item -Path $Env:SystemRoot\WindowsUpdate.log -NewName WindowsUpdate.log.bak -ErrorAction SilentlyContinue
            }
            Write-Host "[Complete]`n" -ForegroundColor Cyan
       
            Write-Host "Resetting Windows Update Policies..." -NoNewline -ForegroundColor Cyan
            Remove-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\WindowsUpdate" -Force -ErrorAction SilentlyContinue
            Remove-Item -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\WindowsUpdate" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" -Name "ResetClient" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" -Name "ResetDataStoreReason" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" -Name "AccountDomainSid" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" -Name "PingID" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" -Name "SusClientId" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" -Name "SusClientIDValidation" -Force -ErrorAction SilentlyContinue
            Start-Process -FilePath CMD -ArgumentList ('/C GPUPDATE /FORCE') -WindowStyle Hidden -Wait
            Write-Host "[Complete]`n" -ForegroundColor Cyan
       
            Write-Host "Resetting the BITS and Windows Update Service Security Descriptors..." -NoNewline -ForegroundColor Cyan
            Start-Process -FilePath CMD -ArgumentList ("/C `"SC.EXE SDSET BITS D:(A;;CCLCSWLOCRRC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLCRSDRCWDWO;;;SO)(A;;CCLCSWRPWPDTLOCRRC;;;SY)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;WD)`"") -WindowStyle Hidden -Wait
            Start-Process -FilePath CMD -ArgumentList ("/C `"SC.EXE SDSET wuauserv D:(A;;CCLCSWLOCRRC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLCRSDRCWDWO;;;SO)(A;;CCLCSWRPWPDTLOCRRC;;;SY)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;WD)`"") -WindowStyle Hidden -Wait
            Start-Process -FilePath CMD -ArgumentList ("/C `"SC.EXE SDSET CryptSvc D:(A;;CCLCSWLOCRRC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLCRSDRCWDWO;;;SO)(A;;CCLCSWRPWPDTLOCRRC;;;SY)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;WD)`"") -WindowStyle Hidden -Wait
            Start-Process -FilePath CMD -ArgumentList ("/C `"SC.EXE SDSET TrustedInstaller D:(A;;CCLCSWLOCRRC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLCRSDRCWDWO;;;SO)(A;;CCLCSWRPWPDTLOCRRC;;;SY)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;WD)`"") -WindowStyle Hidden -Wait
            Write-Host "[Complete]`n" -ForegroundColor Cyan
       
            Write-Host "Reregistering the BITS and Windows Update files..." -NoNewline -ForegroundColor Cyan
            Push-Location
            Set-Location -Path $Env:SystemRoot\System32
            @('atl.dll', 'urlmon.dll', 'mshtml.dll', 'shdocvw.dll', 'browseui.dll', 'jscript.dll', 'vbscript.dll', 'scrrun.dll', 'msxml.dll', 'msxml3.dll', 'msxml6.dll',
                'actxprxy.dll', 'softpub.dll', 'wintrust.dll', 'dssenh.dll', 'rsaenh.dll', 'gpkcsp.dll', 'sccbase.dll', 'slbcsp.dll', 'cryptdlg.dll', 'oleaut32.dll', 'ole32.dll',
                'shell32.dll', 'initpki.dll', 'wuapi.dll', 'wuaueng.dll', 'wuaueng1.dll', 'wucltui.dll', 'wups.dll', 'wups2.dll', 'wuweb.dll', 'qmgr.dll', 'qmgrprxy.dll', 'wucltux.dll',
                'muweb.dll', 'wuwebv.dll') | ForEach-Object -Process { Invoke-Expression -Command ("REGSVR32.EXE /S $PSItem") }
            Pop-Location
            Start-Process -FilePath NETSH -ArgumentList ('WINSOCK RESET') -WindowStyle Hidden -Wait
            Start-Process -FilePath NETSH -ArgumentList ('WINHTTP RESET PROXY') -WindowStyle Hidden -Wait
            Get-BitsTransfer -ErrorAction SilentlyContinue | Remove-BitsTransfer
            Write-Host "[Complete]`n" -ForegroundColor Cyan
       
            Write-Host "Restarting and resetting the BITS, wuauserv, AppIDSvc, CryptSvc, DcomLaunch and TrustedInstaller services..." -NoNewline -ForegroundColor Cyan
            (Get-Service -Name BITS, wuauserv, DcomLaunch -ErrorAction SilentlyContinue) | Start-Service -WarningAction SilentlyContinue | Set-Service -StartupType Automatic
            (Get-Service -Name CryptSvc, AppIDSvc -ErrorAction SilentlyContinue) | Start-Service
            (Get-Service -Name TrustedInstaller -ErrorAction SilentlyContinue) | Set-Service -StartupType Manual
            If ((Get-Service -Name BITS -ErrorAction SilentlyContinue).Status -ne "Running") { Write-Warning "Failed to start the BITS service." }
            If ((Get-Service -Name wuauserv -ErrorAction SilentlyContinue).Status -ne "Running") { Write-Warning "Failed to start the wuauserv service." }
            If ((Get-Service -Name AppIDSvc -ErrorAction SilentlyContinue).Status -ne "Running") { Write-Warning "Failed to start the AppIDSvc service." }
            If ((Get-Service -Name CryptSvc -ErrorAction SilentlyContinue).Status -ne "Running") { Write-Warning "Failed to start the CryptSvc service." }
            If ((Get-Service -Name DcomLaunch -ErrorAction SilentlyContinue).Status -ne "Running") { Write-Warning "Failed to start the DcomLaunch service." }
            Write-Host "[Complete]`n" -ForegroundColor Cyan
       
            Write-Host "Reauthenticating with WSUS servers..." -NoNewline -ForegroundColor Cyan
            Start-Process -FilePath WUAUCLT -ArgumentList ('/RESETAUTHORIZTION /DETECTNOW') -WindowStyle Hidden -Wait
            (New-Object -ComObject Microsoft.Update.AutoUpdate).DetectNow()
            Write-Host "[Complete]`n" -ForegroundColor Cyan
        }
        End
        {
            If ($Restart)
            {
                ForEach ($Count In (1 .. $Restart))
                {
                    Write-Progress -Id 1 -Activity "Restarting $($Env:COMPUTERNAME) in $($Restart.ToString()) seconds." -Status "Waiting for $($Restart.ToString) seconds, $($Restart - $Count) left." -PercentComplete (($Count / $Restart) * 100)
                    Start-Sleep -Seconds 1
                }
                Restart-Computer
            }
            Else
            {
                Write-Host "Reset complete.`n" -ForegroundColor Green
            }
        }
    }
    
    I recently updated this with additional registry entries for removal and the resetting of TrustedInstaller's security descriptors.

    There is also a Restart parameter available that is recommended to use after running this function to clear any additional cache items. Simply use the Restart parameter with an integer representing seconds before the system reboot is initiated. Or you can ignore that parameter and reboot whenever it's more convenient.
     
  2. ShiningDog

    ShiningDog MDL Addicted

    Feb 25, 2018
    564
    523
    30
    Hi, how am i suppose to run this?
    i saved it as .ps1 and its not seem to work.
     
  3. GodHand

    GodHand MDL Senior Member

    Jul 15, 2016
    378
    410
    10
    It works perfectly fine. It's a function, so open PowerShell ISE, copy the contents of the .ps1 into the script pane, hit F5 then type the Start-WindowsCleanup or Reset-WindowsUpdate...whichever you want to run.

    Of you can copy and paste all of its contents in a regular elevated PowerShell console shell and type the function command.
     
  4. GodHand

    GodHand MDL Senior Member

    Jul 15, 2016
    378
    410
    10
    [​IMG]

    After hitting F5 in PowerShell ISE, you can see it automatically detects the command and the parameters available to it.

    [​IMG]

    And just hit enter to run it:

    [​IMG]
     
  5. ShiningDog

    ShiningDog MDL Addicted

    Feb 25, 2018
    564
    523
    30
    Thanks.. :worthy: just tried Windows cleanup, its really great, i guess i'll just replace the ccleaner with this one. I assume it'll work with win 7 too. btw if its possible please consider to make one click cleaner method for it for the convenience.
     
  6. abbodi1406

    abbodi1406 MDL KB0000001

    Feb 19, 2011
    8,102
    27,031
    270
    I know it's possible to use "dot sourcing" to execute functions from ps1 script
    Code:
    . .\script.ps1
    or
    . C:\Downloads\script.ps1
    Code:
    Start-WindowsCleanup
    i recommend not to remove all SoftwareDistribution contents, that will reset WU
    Download folder and maybe *.log is enough

    thanks :)
     
  7. GodHand

    GodHand MDL Senior Member

    Jul 15, 2016
    378
    410
    10
    I personally prefer resetting Windows Update, as it returns all update programs back to their default settings; however, anyone using the function can simply remove that removal command or replace it with something else :)

    And yes you can dot source the script and run the function. Two dots sources the script so you can follow up with the function command itself in the console if you want to pass additional parameters. You would use a single dot to run a script, not a function.[​IMG]