Last active
March 8, 2023 18:47
-
-
Save mattwoolnough/8d86b2ce67755c6909b51a0af19f7a32 to your computer and use it in GitHub Desktop.
Script to allow an AD account the ability to update it's own SPN attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Set-SpnPermission { | |
param( | |
[String]$obj, | |
[switch]$Write, | |
[switch]$Read | |
) | |
### Set-SpnPermission -obj "DOMAIN\svc_SQL" -write -read | |
Import-Module ActiveDirectory | |
$Identity = [security.principal.ntaccount]$obj | |
$sAMAccountName = $obj.Split("\")[1] | |
if(!$write -and !$read){ | |
throw "Missing either -read or -write" | |
} | |
$rootDSE = [adsi]"LDAP://RootDSE" | |
$schemaDN = $rootDSE.psbase.properties["schemaNamingContext"][0] | |
$spnDN = "LDAP://CN=Service-Principal-Name,$schemaDN" | |
$spnEntry = [adsi]$spnDN | |
$guidArg=@("") | |
$guidArg[0]=$spnEntry.psbase.Properties["schemaIDGUID"][0] | |
$spnSecGuid = new-object GUID $guidArg | |
[adsi]$TargetObject = "LDAP://" + (Get-ADUser -Identity $sAMAccountName).DistinguishedName | |
if($read ){$adRight=[DirectoryServices.ActiveDirectoryRights]"ReadProperty" } | |
if($write){$adRight=[DirectoryServices.ActiveDirectoryRights]"WriteProperty"} | |
if($write -and $read){$adRight=[DirectoryServices.ActiveDirectoryRights]"readproperty,writeproperty"} | |
$accessRuleArgs = $identity,$adRight,"Allow",$spnSecGuid,"None" | |
$spnAce = new-object DirectoryServices.ActiveDirectoryAccessRule $accessRuleArgs | |
$TargetObject.psbase.ObjectSecurity.AddAccessRule($spnAce) | |
$TargetObject.psbase.CommitChanges() | |
return $spnAce | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment