Replace owner on subcontainers and objects

Hi Folks

I am trying to write a powershell script which take ownership of a reg key - (relatively easy to do) and subcontainers but struggling to work out how to replace owner on subcontainers and objects of the reg key. This is needed to overwrite deny permissions on a subkey of the regkey I have taken ownership of.

Can anyone point me in the direction of how to do this? I have found a few scripts which partly get the result but not changing permissions on the subcontainers

This can be done manually but would be great to script it.

Thaks in advance