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
    400
    444
    10
    #1 GodHand, Oct 1, 2018
    Last edited: Nov 26, 2018
    I have updated these.

    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 integer for the StateFlags registry property name in case a specific value is required.
            The default value is 1.
    
        .EXAMPLE
            PS C:\> Start-WindowsCleanup
            PS C:\> Start-WindowsCleanup -StateFlags 1234
    #>
        
        [CmdletBinding(ConfirmImpact = 'High',
            SupportsShouldProcess = $true)]
        Param
        (
            [Parameter(Mandatory = $false,
                Position = 0,
                HelpMessage = 'An optional integer for the StateFlags registry property name.')]
            [ValidateRange(1, 9999)]
            [int]$StateFlags = 1
        )
        Begin
        {
            $StateFlagsName = "StateFlags{0:D4}" -f $StateFlags
            $Report = "Start-WindowsCleanup_" + $(Get-Date -Format "MM-dd-yyyy")
            Clear-Host; Start-Transcript -Path "$Env:SystemRoot\Temp\$Report.log"
            Function Clear-Item
            {
                [CmdletBinding()]
                Param
                (
                    [string]$Path,
                    [switch]$Remove
                )
                If ($Remove) { Remove-Item -Path $($Path) -Recurse -Force -Verbose -ErrorAction SilentlyContinue }
                Else { Get-ChildItem -Path $($Path) -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."))
            {
                $BeforeCleanup = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object DriveType -EQ 3 | Select-Object SystemName,
                @{ 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-Item -Path "$Env:TEMP\*"
                Clear-Item -Path "$Env:SystemRoot\Temp\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Temp\*"
                Clear-Item -Path "$Env:SystemRoot\SoftwareDistribution\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\Temporary Internet Files\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatCache\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatUaCache\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\IEDownloadHistory\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\INetCache\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\INetCookies\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Terminal Server Client\Cache\*"
                Clear-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\WER\*"
                Clear-Item -Path "$Env:ProgramData\Microsoft\Windows\WER\*"
                Clear-Item -Path "$Env:SystemRoot\Logs\WindowsUpdate\*"
                Clear-Item -Path "$Env:SystemDrive\swtools\*"
                Clear-Item -Path "$Env:SystemDrive\swsetup\*"
                Clear-Item -Path "$Env:SystemRoot\drivers\*"
                Clear-Item -Path "$Env:SystemDrive\Users\Administrator\Downloads\*"
                Clear-Item -Path "$Env:SystemRoot\minidump\*"
                Clear-Item -Path "$Env:SystemRoot\Prefetch\*"
                Clear-Item -Path "$Env:HOMEDRIVE\inetpub\logs\LogFiles\*"
                Clear-Item -Path "$Env:HOMEDRIVE\PerfLogs\*"
                Clear-Item -Path "$Env:HOMEDRIVE\Intel\*"
                Clear-Item -Path "$Env:HOMEDRIVE\Config.Msi" -Remove
                Clear-Item -Path "$Env:SystemRoot\Logs\CBS\*.log" -Remove
                Clear-Item -Path "$Env:SystemRoot\Logs\DISM\*.log*" -Remove
                Clear-Item -Path "$Env:SystemRoot\memory.dmp" -Remove
                $RecycleBin = (New-Object -ComObject Shell.Application).NameSpace(0xA)
                $RecycleBin.Items() | ForEach-Object -Process { Remove-Item -LiteralPath $_.Path -Recurse -Force -Confirm:$false -Verbose -ErrorAction Ignore }
                $VolumeCache = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches" -ErrorAction SilentlyContinue
                $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()
                $RunningProcess = Get-Process -Name cleanmgr -ErrorAction SilentlyContinue
                While ($($RunningProcess.Refresh(); $RunningProcess.ProcessName)) { Start-Sleep 0.5 }
                Get-Process -Name explorer | Stop-Process -Verbose
                Get-Service -Name wuauserv -ErrorAction SilentlyContinue | Start-Service -Verbose
                Start-Sleep 3
                $VolumeCache = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches" -ErrorAction SilentlyContinue
                $VolumeCache.ForEach{
                    $DisableFlag = @{
                        Path        = $($_.PSPath)
                        Name        = $StateFlagsName
                        ErrorAction = "SilentlyContinue"
                    }
                    Get-ItemProperty @DisableFlag | Remove-ItemProperty -Name $StateFlagsName -ErrorAction SilentlyContinue
                }
                $AfterCleanup = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object DriveType -EQ 3 | Select-Object SystemName,
                @{ 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$BeforeCleanup" -Verbose
                Write-Output "`t`t`tAfter Clean-up:`n$AfterCleanup" -Verbose
            }
        }
        End
        {
            Stop-Transcript
        }
    }
    Start-WindowsCleanup
    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 "Backing-up registry..." -NoNewline -ForegroundColor Cyan
            Start-Process -FilePath REGEDIT -ArgumentList ("/E `"$HOME\Desktop\Backup_$(Get-Random).reg`"") -WindowStyle Hidden -Wait
            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" -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate" -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate" -Recurse -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-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results" -Recurse -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
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" -Name "AUState" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" -Name "LastWaitTimeout" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" -Name "DetectionstartTime" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" -Name "NextDetectionTime" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Reporting" -Name "SamplingValue" -Force -ErrorAction SilentlyContinue
            Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services" -Name "ReregisterAuthorizationCab" -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 "Re-registering 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 -ErrorAction SilentlyContinue | Set-Service -StartupType Automatic
            Get-Service -Name CryptSvc, AppIDSvc -ErrorAction SilentlyContinue | Start-Service -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
            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 -ErrorAction SilentlyContinue
            (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
            }
        }
    }
    Reset-WindowsUpdate
    # SIG # Begin signature block
    # MIIL1AYJKoZIhvcNAQcCoIILxTCCC8ECAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
    # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
    # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUfboPt/2zIHW9eX/br2PMMB4o
    # Wkegggj8MIIDfTCCAmWgAwIBAgIQfY66zkudTZ9EnV2nSZm8oDANBgkqhkiG9w0B
    # AQsFADBFMRQwEgYKCZImiZPyLGQBGRYEVEVDSDEVMBMGCgmSJomT8ixkARkWBU9N
    # TklDMRYwFAYDVQQDEw1PTU5JQy5URUNILUNBMB4XDTE4MDMxMzIxNTY1OFoXDTIz
    # MDMxMzIyMDY1OFowRTEUMBIGCgmSJomT8ixkARkWBFRFQ0gxFTATBgoJkiaJk/Is
    # ZAEZFgVPTU5JQzEWMBQGA1UEAxMNT01OSUMuVEVDSC1DQTCCASIwDQYJKoZIhvcN
    # AQEBBQADggEPADCCAQoCggEBAO6V7MmlK+QuOqWIzrLbmhv9acRXB46vi4RV2xla
    # MTDUimrSyGtpoDQTYK2QZ3idDq1nxrnfAR2XytTwVCcCFoWLpFFRack5k/q3QFFV
    # WP2DbSqoWfNG/EFd0qx8p81X5mH09t1mnN/K+BX1jiBS60rQYTsSGMkSSn/IUxDs
    # sLvatjToctZnCDiqG8SgPdWtVfHRLLMmT0l8paOamO0bpaSSsTpBaan+qiYidnxa
    # eIR23Yvv26Px1kMFYNp5YrWfWJEw5udB4W8DASO8TriypXXpca2jCEkVswNwNW/n
    # Ng7QQqECDVwVm3BVSClNcf1J52uU+Nvx36gKRl5xcogW4h0CAwEAAaNpMGcwEwYJ
    # KwYBBAGCNxQCBAYeBABDAEEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMB
    # Af8wHQYDVR0OBBYEFH/3cqyAb+6RpNGa2+j3ldMI8axTMBAGCSsGAQQBgjcVAQQD
    # AgEAMA0GCSqGSIb3DQEBCwUAA4IBAQBYMivmEQPQpT1OfiPLVFaGFbnKmWo0dTWo
    # vkCQMq54NdUqvnCkOIC9O3nrsBqdQhTPAtDow1C1qWQipGf/JyMCTh9ZIEoz3u4z
    # RsiKMjIlPJkar1OsTsvKcAaya+a10LTcBMfF4DyOFaGqvKNrTaD3MmFQIBblQ8TS
    # QOzQPOXUwY/2IgI9w1AA8VO0N2coYzvj4i79RSQ77eg1iefjBRqs347o4/b7pWtS
    # 95+FBGr7JhhV3i9EI95172O4jmEkmoJQgr2mzvThjp9WiyeyjpnBAikV14YmEIyu
    # DmKue5ZuxG+D3W3ZwFyGytUCHYWwMshTRwI0z236dZG9OhYDSfibMIIFdzCCBF+g
    # AwIBAgITIQAAAAV87PzZFzK4xAAAAAAABTANBgkqhkiG9w0BAQsFADBFMRQwEgYK
    # CZImiZPyLGQBGRYEVEVDSDEVMBMGCgmSJomT8ixkARkWBU9NTklDMRYwFAYDVQQD
    # Ew1PTU5JQy5URUNILUNBMB4XDTE4MDQxODEyMjAzNloXDTE5MDQxODEyMjAzNlow
    # UzEUMBIGCgmSJomT8ixkARkWBFRFQ0gxFTATBgoJkiaJk/IsZAEZFgVPTU5JQzEO
    # MAwGA1UEAxMFVXNlcnMxFDASBgNVBAMTC0JlblRoZUdyZWF0MIIBIjANBgkqhkiG
    # 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9xWMMTEOCpdnZu3eDTVbytEzoTnHQYeS/2jg
    # wGLYU3+43C3viMoNVj+nLANJydTIRW5Dca+6JfO8UH25kf0XQ+AiXirQfjb9ec9u
    # I+au+krmlL1fSR076lPgYzqnqPMQzOER8U2J2+uF18UtxEVO3rq7Cnxlich4jXzy
    # gTy8XiNSAfUGR1nfq7HjahJ/CKopwl/7NcfmV5ZDzogRob1eErOPJXGAkewJuKqp
    # /qItYzGH+9XADCyO0GYVIOsXNIE0Ho0bdBPZ3eDdamL1vocTlEkTe0/drs3o2AkS
    # qcgg2I0uBco/p8CxCR7Tfq2zX1DFW9B7+KGNobxq+l+V15rTMwIDAQABo4ICUDCC
    # AkwwJQYJKwYBBAGCNxQCBBgeFgBDAG8AZABlAFMAaQBnAG4AaQBuAGcwEwYDVR0l
    # BAwwCgYIKwYBBQUHAwMwDgYDVR0PAQH/BAQDAgeAMB0GA1UdDgQWBBSIikO7ZjAP
    # GlMAUcP2kulHiqpJnDAfBgNVHSMEGDAWgBR/93KsgG/ukaTRmtvo95XTCPGsUzCB
    # yQYDVR0fBIHBMIG+MIG7oIG4oIG1hoGybGRhcDovLy9DTj1PTU5JQy5URUNILUNB
    # LENOPURPUkFETyxDTj1DRFAsQ049UHVibGljJTIwS2V5JTIwU2VydmljZXMsQ049
    # U2VydmljZXMsQ049Q29uZmlndXJhdGlvbixEQz1PTU5JQyxEQz1URUNIP2NlcnRp
    # ZmljYXRlUmV2b2NhdGlvbkxpc3Q/YmFzZT9vYmplY3RDbGFzcz1jUkxEaXN0cmli
    # dXRpb25Qb2ludDCBvgYIKwYBBQUHAQEEgbEwga4wgasGCCsGAQUFBzAChoGebGRh
    # cDovLy9DTj1PTU5JQy5URUNILUNBLENOPUFJQSxDTj1QdWJsaWMlMjBLZXklMjBT
    # ZXJ2aWNlcyxDTj1TZXJ2aWNlcyxDTj1Db25maWd1cmF0aW9uLERDPU9NTklDLERD
    # PVRFQ0g/Y0FDZXJ0aWZpY2F0ZT9iYXNlP29iamVjdENsYXNzPWNlcnRpZmljYXRp
    # b25BdXRob3JpdHkwMQYDVR0RBCowKKAmBgorBgEEAYI3FAIDoBgMFkJlblRoZUdy
    # ZWF0QE9NTklDLlRFQ0gwDQYJKoZIhvcNAQELBQADggEBAD1ZkdqIaFcqxTK1YcVi
    # QENxxkixwVHJW8ZATwpQa8zQBh3B1cMromiR6gFvPmphMI1ObRtuTohvuZ+4tK7/
    # IohAt6TwzyDFqY+/HzoNCat07Vb7DrA2fa+QMOl421kVUnZyYLI+gEod/zJqyuk8
    # ULBmUxCXxxH26XVC016AuoOedKwzBgAFyIDlIAivZcSOtaSyALJSZ2Pk29R69dp5
    # ICb+zCXCWPQJkbsU6eTlZAwaMmR2Vx4TQeDl49YIIwoDXDT4zBTcJ6n2k6vHQDWR
    # K9zaF4qAD9pwlQICbLgTeZBz5Bz2sXzhkPsmY6LNKTAOnuk0QbjsKXSKoB/QRAip
    # FiUxggJCMIICPgIBATBcMEUxFDASBgoJkiaJk/IsZAEZFgRURUNIMRUwEwYKCZIm
    # iZPyLGQBGRYFT01OSUMxFjAUBgNVBAMTDU9NTklDLlRFQ0gtQ0ECEyEAAAAFfOz8
    # 2RcyuMQAAAAAAAUwCQYFKw4DAhoFAKCBvDAZBgkqhkiG9w0BCQMxDAYKKwYBBAGC
    # NwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQx
    # FgQUpv2OURmk/UdTK/UzzjjlQd7/I5EwXAYKKwYBBAGCNwIBDDFOMEygSoBIAFIA
    # ZQBzAGUAdABzACAAYQBuAGQAIABjAGwAZQBhAG4AcwAtAHUAcAAgAFcAaQBuAGQA
    # bwB3AHMAIABVAHAAZABhAHQAZQAuMA0GCSqGSIb3DQEBAQUABIIBAK3izNSHeFm6
    # KlFq1dHJT/S1cFzKMLB6ZlvYHRXOoFYXU/Rnwb+MZIJmXsjCroWTW8V5DZxg+EpG
    # 6US27BQfboOn5ai/87HkVR8kQ7mL7LJ8sNGaCTk9vyy+sXQBxLSk2m8a0X32ocjZ
    # 5a1s/yj2LjGoMItiiVKQOkHALzOo+zjbE/wO/oxAk6phXoLi0Mm6X5oCCB+GY0SH
    # r674oU941AkQRe3KHHXMG/Kxsgz1GFMsbXfFa8bcP+DLJMBYVaidiAzqxZT/782R
    # ylH5BPJSm/1R6CIaerF1oan8x4PbH0SiCGDcEoGGDDi1nS0KAOSbJA78oCb1pzwF
    # SFzcesS2coc=
    # SIG # End signature block
    
    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. 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
    400
    444
    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
    400
    444
    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. 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,401
    28,892
    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
    400
    444
    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]