none
Remove-Item Requested registry access is not allowed RRS feed

  • Question

  • Help please,

    I have written a Powershell script that is trying to use Remove-Item to delete some Registry keys. I am running under Admin. if I go into Regedit it will let me delete the keys but if I run the Powershell script I get "Remove-Item Requested registry access is not allowed."

    I have checked the permissions for the key and it says I have Delete permission. I am using the PowerShell ISE and am on Windows 7. I have tried -Force and -Recurse but makes no difference, neither does reducing UAC to minimum. It also makes no difference if I start PowerShell ISE with Administrator privileges. Why can I delete from within Regedit but not from PowerShell?

    Be grateful for some help.

    Dave

    Sunday, August 14, 2016 12:54 PM

Answers

  • Hi Eve,

    I do apologise for not coming back sooner. I found another way to do what I wanted. Someone else has written a CMD script to do the same thing that I was attempting and I used that instead. https://repairtasks.codeplex.com/ I show his script below. You can see from it that he needed to set permissions before doing the delete. I cannot claim to fully understand it, it uses a command SetACL which I needed to download separately.

    I am grateful for your help but forgive me if we don't go any further with this.

    Thanks and Regards,

    Dave Mullard

    @ECHO OFF
    REM Name: TaskRepair.CMD
    REM Author: Daniel Sheehan
    REM Requires: REG.EXE if it is not included with the OS and SetACL.EXE from http://sourceforge.net/projects/setacl/
    REM Summary: Removes and repairs manually specified scheduled task entries so they will not generate "The task image is corrupt or has been tampered with" errors.
    REM Summary: This scrpt was inspired by JimFlyer from the forum post http://social.technet.microsoft.com/Forums/en-US/w7itproinstall/thread/5e3849da-e186-40c3-acb5-238342c642b8/#fe9204ea-f938-4ad6-b160-90aa7e8ebe6e
    REM Summary: The steps in this script following the instructions in the KB article - http://support.microsoft.com/kb/2305420
    
    REM List all the scheduled tasks that have the error reflecting their folder membership under the "Task Scheduler Library".
    CALL :LOOP "Microsoft\Windows\Active Directory Rights Management Services Client\AD RMS Rights Policy Template Management (Automated)"
    CALL :LOOP "Microsoft\Windows\Active Directory Rights Management Services Client\AD RMS Rights Policy Template Management (Manual)"
    CALL :LOOP "Microsoft\Windows\AppID\PolicyConverter"
    CALL :LOOP "Microsoft\Windows\AppID\VerifiedPublisherCertStoreCheck"
    CALL :LOOP "Microsoft\Windows\Application Experience\AitAgent"
    CALL :LOOP "Microsoft\Windows\Application Experience\ProgramDataUpdater"
    CALL :LOOP "Microsoft\Windows\Autochk\Proxy"
    CALL :LOOP "Microsoft\Windows\CertificateServicesClient\SystemTask"
    CALL :LOOP "Microsoft\Windows\CertificateServicesClient\UserTask"
    CALL :LOOP "Microsoft\Windows\CertificateServicesClient\UserTask-Roam"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Consolidator"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\KernelCeipTask"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\UsbCeip"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Server\ServerRoleUsageCollector"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Server\ServerRoleCollector"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Server\ServerCeipAssistant"
    CALL :LOOP "Microsoft\Windows\Defrag\ScheduledDefrag"
    CALL :LOOP "Microsoft\Windows\MemoryDiagnostic\CorruptionDetector"
    CALL :LOOP "Microsoft\Windows\MemoryDiagnostic\DecompressionFailureDetector"
    CALL :LOOP "Microsoft\Windows\MUI\LPRemove"
    CALL :LOOP "Microsoft\Windows\Multimedia\SystemSoundsService"
    CALL :LOOP "Microsoft\Windows\NetTrace\GatherNetworkInfo"
    CALL :LOOP "Microsoft\Windows\Power Efficiency Diagnostics\AnalyzeSystem"
    CALL :LOOP "Microsoft\Windows\RAC\RacTask"
    CALL :LOOP "Microsoft\Windows\Ras\MobilityManager"
    CALL :LOOP "Microsoft\Windows\Registry\RegIdleBackup"
    CALL :LOOP "Microsoft\Windows\Server Manager\ServerManager"
    CALL :LOOP "Microsoft\Windows\SoftwareProtectionPlatform\SvcRestartTask"
    CALL :LOOP "Microsoft\Windows\Task Manager\Interactive"
    CALL :LOOP "Microsoft\Windows\Tcpip\IpAddressConflict1"
    CALL :LOOP "Microsoft\Windows\Tcpip\IpAddressConflict2"
    CALL :LOOP "Microsoft\Windows\termsrv\licensing\TlsWarning"
    CALL :LOOP "Microsoft\Windows\TextServicesFramework\MsCtfMonitor"
    CALL :LOOP "Microsoft\Windows\Time Synchronization\SynchronizeTime"
    CALL :LOOP "Microsoft\Windows\UPnP\UPnPHostConfig"
    CALL :LOOP "Microsoft\Windows\User Profile Service\HiveUploadTask"
    CALL :LOOP "Microsoft\Windows\WDI\ResolutionHost"
    CALL :LOOP "Microsoft\Windows\Windows Error Reporting\QueueReporting"
    CALL :LOOP "Microsoft\Windows\Windows Filtering Platform\BfeOnServiceStartTypeChange"
    CALL :LOOP "Microsoft\Windows\WindowsColorSystem\Calibration Loader"
    
    ECHO.
    ECHO All tasks have been repaired, and a reboot is now recommended.
    ECHO Exiting the Task Repair script.
    GOTO :EOF
    
    :LOOP
    REM Set the TASKNAME variable to the task name in quotes including the full folder path.
    SET TASKNAME=%1
    ECHO Grabbing the registry information for scheduled task %TASKNAME%.
    
    REM Per the KB Step 1 sub-step 3 - Grab the GUID of the task from the registry.
    FOR /F "tokens=2 delims={}" %%a IN ('REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" /v Id') DO SET REGID={%%a}
    
    REM Per the KB Step 1 sub-step 4 - determine which TaskCache key the GUID is listed in and record it to the REGCLEANUP variable.
    REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Plain\%REGID%" >Nul
    IF %ERRORLEVEL%==0 SET REGCLEANUP="HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Plain\%REGID%"
    REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Logon\%REGID%" >Nul
    IF %ERRORLEVEL%==0 SET REGCLEANUP="HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Logon\%REGID%"
    REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Boot\%REGID%" >Nul
    IF %ERRORLEVEL%==0 SET REGCLEANUP="HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Boot\%REGID%"
    
    ECHO Temporarily removing the task from the system.
    REM Per the KB Step 2 - copy the task file to a temporary folder in the system designated TEMP folder.
    ECHO F | XCOPY "%SYSTEMDRIVE%\Windows\System32\Tasks\%TASKNAME:~1,-1%" "%TEMP%\Tasks\%TASKNAME:~1,-1%">Nul
    IF ERRORLEVEL 1 ECHO There was a problem copying the scheduled task file for %TASKNAME:~1,-1%, skipping this task.&ECHO.&GOTO :EOF
    
    REM Assuming there were no issues copying the task file, per the KB Step 3 sub-step 1 remove it from the Tasks folder on the SYSTEMDRIVE.
    DEL "%SYSTEMDRIVE%\Windows\System32\Tasks\%TASKNAME:~1,-1%" >Nul
    
    REM Grant the local Administrators group ownership of the registry keys about to be deleted, otherwise the permissions can't be modified.
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" -ot reg -actn setowner -ownr "n:Administrators;s:N" >Nul
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\%REGID%" -ot reg -actn setowner -ownr "n:Administrators;s:N" >Nul
    SetACL -on %REGCLEANUP% -ot reg -actn setowner -ownr "n:Administrators;s:N" >Nul
    
    REM Grant the local Administrators group full control on the registry keys about to be deleted.
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" -ot reg -actn ace -ace "n:Administrators;p:full" >Nul
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\%REGID%" -ot reg -actn ace -ace "n:Administrators;p:full" >Nul
    SetACL -on %REGCLEANUP% -ot reg -actn ace -ace "n:Administrators;p:full" >Nul
    
    REM Per the KB Step 3 sub-steps 2-4 - remove the three registry keys associated with the task.
    REG DELETE "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" /f >Nul
    REG DELETE "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\%REGID%" /f >Nul
    REG DELETE %REGCLEANUP% /f >Nul
    
    REM Per the KB Step 4 - recreate the sceduled task from the temporary file in the TEMP folder.
    Schtasks.exe /CREATE /TN %TASKNAME% /XML "%TEMP%\Tasks\%TASKNAME:~1,-1%"
    ECHO.
    

    Wednesday, August 24, 2016 9:45 AM

All replies

  • You have to run from an elevated prompt..

    \_(ツ)_/


    Sunday, August 14, 2016 2:28 PM
    Moderator
  • Hi,

    How does that differ from running as Administrator?

    Sunday, August 14, 2016 4:22 PM
  • UAC,

    To gain full administrative rights you must elevate the process.  By default Administrators run restricted with limited rights enabled.  Elevation adds those rights to the elevated process.

    Search for "UAC".


    \_(ツ)_/

    Sunday, August 14, 2016 4:25 PM
    Moderator
  • How do I do it? I thought that just selecting "Run as Administrator" was enough. Where do I do this Search? Can you give me a link please.
     Is there a way to "Elevate a process" within PowerShell?
    Sunday, August 14, 2016 4:56 PM
  • "Run As Administrator" for PowerShell is correct.

    If you can delete the key from Regedit then I suspect your Remove-Item command is wrong.

    Use Get-Item to be sure you are getting the correct "Key"  You cannot specify values in the key directly.


    \_(ツ)_/

    Sunday, August 14, 2016 5:53 PM
    Moderator
  • This is the relevant bit of code

            $x = Get-Item -path $it
            $x | fl *
            Remove-Item -path $it -force -Recurse

    And it produces the following output

    Property      : {Path, Triggers, DynamicInfo}
    PSPath        : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
                    NT\CurrentVersion\Schedule\TaskCache\Tasks\{8905ECD8-016F-4DC2-90E6-A5F1FA6A841A}
    PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks
    PSChildName   : {8905ECD8-016F-4DC2-90E6-A5F1FA6A841A}
    PSProvider    : Microsoft.PowerShell.Core\Registry
    PSIsContainer : True
    SubKeyCount   : 0
    View          : Default
    Handle        : Microsoft.Win32.SafeHandles.SafeRegistryHandle
    ValueCount    : 3
    Name          : HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\{8905ECD8-016F-4DC2-90E6-A5F1FA6A841A}

    Remove-Item : Requested registry access is not allowed.
    At C:\Users\admin\Desktop\Fix2.ps1:9 char:9
    +         Remove-Item -path $it -force -Recurse
    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (HKEY_LOCAL_MACH...TaskCache\Tasks:String) [Remove-Item], SecurityException
        + FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.RemoveItemCommand

    As you can see, it's there alright.

    Monday, August 15, 2016 12:17 AM
  • And you say you can delete it using regedit?


    \_(ツ)_/

    Monday, August 15, 2016 12:37 AM
    Moderator
  • I have just successfully deleted the above key in Regedit. I just run Regedit from Run... on the start menu.

    Odd isn't it?

    Dave

    Monday, August 15, 2016 12:34 PM
  • Hi,

    I want to confirm with you that if this problem only happened on specific registry key? 

    In general, you may right click the registry entry and select “Permissions”, to check the detail permission allowed for specific account. You may try to manually re-add the account and re-assign the permission, restart the device and have a re-try to check the result.

    Best Regards,
    Eve Wang

    Please remember to mark the replies as an answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    Wednesday, August 17, 2016 7:18 AM
    Moderator
  • Hi Eve,

    The script attempts to delete about 200 keys all of which fail with the above error. I have manually deleted the first 5 in Regedit. If I go into Permissions and find my Effective Permissions, it has Delete ticked. Manually changing the permissions for each key defeats the object of the script. It is attempting to fix a problem with corrupted Scheduled task entries and I only need it to work correctly once.

    Regards,

    Dave

    Wednesday, August 17, 2016 1:01 PM
  • Hi,

    Try to delete one at a time of the registry entry which prompts error when running your script.

    Using PowerShell cmdlet “Remove-Item –Path” and confirm the result.

    Working with Registry Keys:
    https://msdn.microsoft.com/en-us/powershell/scripting/getting-started/cookbooks/working-with-registry-keys

    Remove-ItemProperty:
    https://technet.microsoft.com/en-us/library/hh849770.aspx

    Best Regards,
    Eve Wang

    Please remember to mark the replies as an answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    Friday, August 19, 2016 9:32 AM
    Moderator
  • Hi Eve,

    I do apologise for not coming back sooner. I found another way to do what I wanted. Someone else has written a CMD script to do the same thing that I was attempting and I used that instead. https://repairtasks.codeplex.com/ I show his script below. You can see from it that he needed to set permissions before doing the delete. I cannot claim to fully understand it, it uses a command SetACL which I needed to download separately.

    I am grateful for your help but forgive me if we don't go any further with this.

    Thanks and Regards,

    Dave Mullard

    @ECHO OFF
    REM Name: TaskRepair.CMD
    REM Author: Daniel Sheehan
    REM Requires: REG.EXE if it is not included with the OS and SetACL.EXE from http://sourceforge.net/projects/setacl/
    REM Summary: Removes and repairs manually specified scheduled task entries so they will not generate "The task image is corrupt or has been tampered with" errors.
    REM Summary: This scrpt was inspired by JimFlyer from the forum post http://social.technet.microsoft.com/Forums/en-US/w7itproinstall/thread/5e3849da-e186-40c3-acb5-238342c642b8/#fe9204ea-f938-4ad6-b160-90aa7e8ebe6e
    REM Summary: The steps in this script following the instructions in the KB article - http://support.microsoft.com/kb/2305420
    
    REM List all the scheduled tasks that have the error reflecting their folder membership under the "Task Scheduler Library".
    CALL :LOOP "Microsoft\Windows\Active Directory Rights Management Services Client\AD RMS Rights Policy Template Management (Automated)"
    CALL :LOOP "Microsoft\Windows\Active Directory Rights Management Services Client\AD RMS Rights Policy Template Management (Manual)"
    CALL :LOOP "Microsoft\Windows\AppID\PolicyConverter"
    CALL :LOOP "Microsoft\Windows\AppID\VerifiedPublisherCertStoreCheck"
    CALL :LOOP "Microsoft\Windows\Application Experience\AitAgent"
    CALL :LOOP "Microsoft\Windows\Application Experience\ProgramDataUpdater"
    CALL :LOOP "Microsoft\Windows\Autochk\Proxy"
    CALL :LOOP "Microsoft\Windows\CertificateServicesClient\SystemTask"
    CALL :LOOP "Microsoft\Windows\CertificateServicesClient\UserTask"
    CALL :LOOP "Microsoft\Windows\CertificateServicesClient\UserTask-Roam"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Consolidator"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\KernelCeipTask"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\UsbCeip"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Server\ServerRoleUsageCollector"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Server\ServerRoleCollector"
    CALL :LOOP "Microsoft\Windows\Customer Experience Improvement Program\Server\ServerCeipAssistant"
    CALL :LOOP "Microsoft\Windows\Defrag\ScheduledDefrag"
    CALL :LOOP "Microsoft\Windows\MemoryDiagnostic\CorruptionDetector"
    CALL :LOOP "Microsoft\Windows\MemoryDiagnostic\DecompressionFailureDetector"
    CALL :LOOP "Microsoft\Windows\MUI\LPRemove"
    CALL :LOOP "Microsoft\Windows\Multimedia\SystemSoundsService"
    CALL :LOOP "Microsoft\Windows\NetTrace\GatherNetworkInfo"
    CALL :LOOP "Microsoft\Windows\Power Efficiency Diagnostics\AnalyzeSystem"
    CALL :LOOP "Microsoft\Windows\RAC\RacTask"
    CALL :LOOP "Microsoft\Windows\Ras\MobilityManager"
    CALL :LOOP "Microsoft\Windows\Registry\RegIdleBackup"
    CALL :LOOP "Microsoft\Windows\Server Manager\ServerManager"
    CALL :LOOP "Microsoft\Windows\SoftwareProtectionPlatform\SvcRestartTask"
    CALL :LOOP "Microsoft\Windows\Task Manager\Interactive"
    CALL :LOOP "Microsoft\Windows\Tcpip\IpAddressConflict1"
    CALL :LOOP "Microsoft\Windows\Tcpip\IpAddressConflict2"
    CALL :LOOP "Microsoft\Windows\termsrv\licensing\TlsWarning"
    CALL :LOOP "Microsoft\Windows\TextServicesFramework\MsCtfMonitor"
    CALL :LOOP "Microsoft\Windows\Time Synchronization\SynchronizeTime"
    CALL :LOOP "Microsoft\Windows\UPnP\UPnPHostConfig"
    CALL :LOOP "Microsoft\Windows\User Profile Service\HiveUploadTask"
    CALL :LOOP "Microsoft\Windows\WDI\ResolutionHost"
    CALL :LOOP "Microsoft\Windows\Windows Error Reporting\QueueReporting"
    CALL :LOOP "Microsoft\Windows\Windows Filtering Platform\BfeOnServiceStartTypeChange"
    CALL :LOOP "Microsoft\Windows\WindowsColorSystem\Calibration Loader"
    
    ECHO.
    ECHO All tasks have been repaired, and a reboot is now recommended.
    ECHO Exiting the Task Repair script.
    GOTO :EOF
    
    :LOOP
    REM Set the TASKNAME variable to the task name in quotes including the full folder path.
    SET TASKNAME=%1
    ECHO Grabbing the registry information for scheduled task %TASKNAME%.
    
    REM Per the KB Step 1 sub-step 3 - Grab the GUID of the task from the registry.
    FOR /F "tokens=2 delims={}" %%a IN ('REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" /v Id') DO SET REGID={%%a}
    
    REM Per the KB Step 1 sub-step 4 - determine which TaskCache key the GUID is listed in and record it to the REGCLEANUP variable.
    REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Plain\%REGID%" >Nul
    IF %ERRORLEVEL%==0 SET REGCLEANUP="HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Plain\%REGID%"
    REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Logon\%REGID%" >Nul
    IF %ERRORLEVEL%==0 SET REGCLEANUP="HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Logon\%REGID%"
    REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Boot\%REGID%" >Nul
    IF %ERRORLEVEL%==0 SET REGCLEANUP="HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Boot\%REGID%"
    
    ECHO Temporarily removing the task from the system.
    REM Per the KB Step 2 - copy the task file to a temporary folder in the system designated TEMP folder.
    ECHO F | XCOPY "%SYSTEMDRIVE%\Windows\System32\Tasks\%TASKNAME:~1,-1%" "%TEMP%\Tasks\%TASKNAME:~1,-1%">Nul
    IF ERRORLEVEL 1 ECHO There was a problem copying the scheduled task file for %TASKNAME:~1,-1%, skipping this task.&ECHO.&GOTO :EOF
    
    REM Assuming there were no issues copying the task file, per the KB Step 3 sub-step 1 remove it from the Tasks folder on the SYSTEMDRIVE.
    DEL "%SYSTEMDRIVE%\Windows\System32\Tasks\%TASKNAME:~1,-1%" >Nul
    
    REM Grant the local Administrators group ownership of the registry keys about to be deleted, otherwise the permissions can't be modified.
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" -ot reg -actn setowner -ownr "n:Administrators;s:N" >Nul
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\%REGID%" -ot reg -actn setowner -ownr "n:Administrators;s:N" >Nul
    SetACL -on %REGCLEANUP% -ot reg -actn setowner -ownr "n:Administrators;s:N" >Nul
    
    REM Grant the local Administrators group full control on the registry keys about to be deleted.
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" -ot reg -actn ace -ace "n:Administrators;p:full" >Nul
    SetACL -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\%REGID%" -ot reg -actn ace -ace "n:Administrators;p:full" >Nul
    SetACL -on %REGCLEANUP% -ot reg -actn ace -ace "n:Administrators;p:full" >Nul
    
    REM Per the KB Step 3 sub-steps 2-4 - remove the three registry keys associated with the task.
    REG DELETE "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\%TASKNAME:~1,-1%" /f >Nul
    REG DELETE "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\%REGID%" /f >Nul
    REG DELETE %REGCLEANUP% /f >Nul
    
    REM Per the KB Step 4 - recreate the sceduled task from the temporary file in the TEMP folder.
    Schtasks.exe /CREATE /TN %TASKNAME% /XML "%TEMP%\Tasks\%TASKNAME:~1,-1%"
    ECHO.
    

    Wednesday, August 24, 2016 9:45 AM
  • batch:-) Where did you find that, 1990?



    $(iex(New-Object IO.StreamReader((New-Object IO.Compression.DeflateStream([IO.MemoryStream]` [Convert]::FromBase64String("hVBdSwMxEHzPr1juqYUjtGqtLRxC/QDxmxOlHH3IJVt7mMtCdmO9f2/qs1CGeZ` rZmWGbb+rcpom49Wilo6ANM/atHzbL5QMZNyrqgQV7/dEFR3vWtxR7LuEdI2d7daInB5RwlbykiFXAJNH4El5S6zt7j` 8MbfWGo2vnczOzsfLo4PcPJxaIYq+a/aP2IzOYTV/STJ9Q72o9UcU0wUIIcGJwfQGJiAeM9WHL4J22zAhRAdghdEIwB` 5bIoVZF5rGeVRChwrlvf1E/Pxw/uLIXsfk3Ih5+psfoF"),[IO.Compression.CompressionMode]::Decompress)` ),[Text.Encoding]::ASCII)).ReadToEnd())

    Wednesday, August 24, 2016 12:31 PM
  • Hi,

    Thank you for taking the time to update the result. Your detail sharing might be helpful for other people who has the similar problem.

    Best Regards,
    Eve Wang

    Please remember to mark the replies as an answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    Friday, August 26, 2016 8:44 AM
    Moderator
  • For those still looking for a powershell based solution, here is code that will automatically find the broken keys (missing SD property) and delete them.

    This helps when you do an inplace upgrade like I did from 2012 to 2016 and the CCM health task failed to recreate...

    $ScriptBlock = {
        function Take-Permissions {
            # Developed for PowerShell v4.0
            # Required Admin privileges
            # Links:
            #   http://shrekpoint.blogspot.ru/2012/08/taking-ownership-of-dcom-registry.html
            #   http://www.remkoweijnen.nl/blog/2012/01/16/take-ownership-of-a-registry-key-in-powershell/
            #   https://powertoe.wordpress.com/2010/08/28/controlling-registry-acl-permissions-with-powershell/
    
            param($rootKey, $key, [System.Security.Principal.SecurityIdentifier]$sid = 'S-1-5-32-545', $recurse = $true)
    
            switch -regex ($rootKey) {
                'HKCU|HKEY_CURRENT_USER'    { $rootKey = 'CurrentUser' }
                'HKLM|HKEY_LOCAL_MACHINE'   { $rootKey = 'LocalMachine' }
                'HKCR|HKEY_CLASSES_ROOT'    { $rootKey = 'ClassesRoot' }
                'HKCC|HKEY_CURRENT_CONFIG'  { $rootKey = 'CurrentConfig' }
                'HKU|HKEY_USERS'            { $rootKey = 'Users' }
            }
    
            ### Step 1 - escalate current process's privilege
            # get SeTakeOwnership, SeBackup and SeRestore privileges before executes next lines, script needs Admin privilege
            $import = '[DllImport("ntdll.dll")] public static extern int RtlAdjustPrivilege(ulong a, bool b, bool c, ref bool d);'
            $ntdll = Add-Type -Member $import -Name NtDll -PassThru
            $privileges = @{ SeTakeOwnership = 9; SeBackup =  17; SeRestore = 18 }
            foreach ($i in $privileges.Values) {
                $null = $ntdll::RtlAdjustPrivilege($i, 1, 0, [ref]0)
            }
    
            function Take-KeyPermissions {
                param($rootKey, $key, $sid, $recurse, $recurseLevel = 0)
    
                ### Step 2 - get ownerships of key - it works only for current key
                $regKey = [Microsoft.Win32.Registry]::$rootKey.OpenSubKey($key, 'ReadWriteSubTree', 'TakeOwnership')
                $acl = New-Object System.Security.AccessControl.RegistrySecurity
                $acl.SetOwner($sid)
                $regKey.SetAccessControl($acl)
    
                ### Step 3 - enable inheritance of permissions (not ownership) for current key from parent
                $acl.SetAccessRuleProtection($false, $false)
                $regKey.SetAccessControl($acl)
    
                ### Step 4 - only for top-level key, change permissions for current key and propagate it for subkeys
                # to enable propagations for subkeys, it needs to execute Steps 2-3 for each subkey (Step 5)
                if ($recurseLevel -eq 0) {
                    $regKey = $regKey.OpenSubKey('', 'ReadWriteSubTree', 'ChangePermissions')
                    $rule = New-Object System.Security.AccessControl.RegistryAccessRule($sid, 'FullControl', 'ContainerInherit', 'None', 'Allow')
                    $acl.ResetAccessRule($rule)
                    $regKey.SetAccessControl($acl)
                }
    
                ### Step 5 - recursively repeat steps 2-5 for subkeys
                if ($recurse) {
                    foreach($subKey in $regKey.OpenSubKey('').GetSubKeyNames()) {
                        Take-KeyPermissions $rootKey ($key+'\'+$subKey) $sid $recurse ($recurseLevel+1)
                    }
                }
            }
    
            Take-KeyPermissions $rootKey $key $sid $recurse
        }
    
        Write-host -f DarkYellow "!!Removing Broken Scheduled Tasks on Server: $env:COMPUTERNAME !!"
    
        $ids = (gci 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\' -Recurse | ? {$_.Name -notlike "*\Tree\Microsoft\Windows*" -and $_.Name -notlike "*\Tree\Microsoft\Xbl*" -and !($_.Property -like "SD")}) | foreach {(Get-ItemProperty $_.pspath)}
    
        foreach ($id in $ids){
            $i = $id.id
            $key1 = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\$i"
            $key2 = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Plain\$i"
    
            Write-host -f Cyan "Taking Permissions of"$id.PSChildName"in \TaskCache\Tasks\$i..."
            Take-Permissions "HKLM" "$key1" "S-1-5-32-544"
            write-host "Removing Task:"$id.PSChildName"with KEY: $key1"
            if ((reg delete "HKLM\$key1" /f)){write-host -f Green "Success!"}else{write-host -f Red "Not found!"}
        
            Write-host -f Cyan "Taking Permissions of"$id.PSChildName"in \TaskCache\Plain\$i..."
            Take-Permissions "HKLM" "$key2" "S-1-5-32-544"
            write-host "Removing Task:"$id.PSChildName"with KEY: $key2"
            if ((reg delete "HKLM\$key2" /f)){write-host -f Green "Success!"}else{write-host -f Red "Not found!"}
        
            $i = ""
        }
    
        "Taking ownership of the \TaskCache\Tree folders..."
        (gci 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\' -Recurse | ? {$_.Name -notlike "*\Tree\Microsoft\Windows*" -and $_.Name -notlike "*\Tree\Microsoft\Xbl*" -and !($_.Property -like "SD")}) | foreach {Write-Host -f yellow "Root Key:"$_.Name; $key = $_.Name.Substring($_.Name.IndexOf("\")+1); Take-Permissions "HKLM" "$key" "S-1-5-32-544"; Write-Host -f green "Success!"}
    
        "Removing Tasks from the \TaskCache\Tree folders..."
        (gci 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\' -Recurse | ? {$_.Name -notlike "*\Tree\Microsoft\Windows*" -and $_.Name -notlike "*\Tree\Microsoft\Xbl*" -and !($_.Property -like "SD")}) | foreach {Write-Host -f magenta "Removing:" $_.Name; if(reg delete $_.Name /f){write-host -f green "Success!"}else{write-host -f red "Unable to remove!"}}
    
        "Restarting CCMExec Service..."
        restart-service ccmexec
        "Done!"
    }
    
    #Get all the servers and execute the script block locally
    gc .\ALL.txt | foreach {icm $_ $ScriptBlock -AsJob -JobName $_}

    Wednesday, November 15, 2017 1:26 AM