Set-GPRegistryValue fails randomly if not running in interactive session Windows Server 2019


I'm trying to create a new GPO, configure some settings, and after that link it to an OU using PowerShell. My script looks like this:

New-GPO -Name $GPOname -Comment "My new GPO"
Set-GPRegistryValue -Name $GPOname -Key "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System" -ValueName DisableRegistryTools -Type DWORD -Value 1
# many Set-GPRegistryValues more
New-GPLink -Name $GPOname -Target $TargetOU

The settings are all administrative templates in the user configuration. The script will not run in an interactive session, it will be triggered automatically.

If it's getting triggered, it fails on setting random settings (1 - 2 on each run) with the following error:

 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo          : NotSpecified: (:) [Set-GPRegistryValue], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.GroupPolicy.Commands.SetGPRegistryValueCommand
+ PSComputerName        : localhost 

If I run the script in interactive mode (PowerShell ISE) it works fine. However, if I execute it in the ISE, but wrap it in an Invoke-Command block like this:

Invoke-Command -ComputerName localhost -credential $DomainAdminCreds -ScriptBlock { #Script from above }

it fails with the same error. What it makes really strange is, that I have another script, which is basically the same, but only applies admin templates in the computer configuration scope and this one works fine every time.

I've searched the web already and verified, that SYSVOL (C:\Windows\SYSVOL) permissions are correct. Also the account, that is used is member of Domain Admins, Enterprise Admins, Schema Admins and Group Policy Creator owner.

The scripts runs directly on a Windows Server 2019 Domain Controller, which is freshly installed, functional level is 2016.

Does anybody knows how to resolve this issue? Thank you!

Edit: It seems to be a timing issue. After adding a Start-Sleep -s 5 after each setting, it seems to work. Does anybody know more about this?

asked on Server Fault May 5, 2021 by Jonas Hüsser • edited May 5, 2021 by Jonas Hüsser

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0