Skip to content

Instantly share code, notes, and snippets.

@mattwoolnough
Last active March 8, 2023 18:47
Show Gist options
  • Save mattwoolnough/8d86b2ce67755c6909b51a0af19f7a32 to your computer and use it in GitHub Desktop.
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
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