0

I'm trying to assign permissions to AD OU's using powershell script that is supposed to create a new object of type System.Security.Principal.NTAccount and System.DirectoryServices.ActiveDirectoryAccessRule, The code I have right now is working without alternate credentials but now I need to use the same code with alternate credentials.

Working Code without Alternate Credentials:

$ADSI = [ADSI]"LDAP://$OUPath"

$NTAccount = New-Object System.Security.Principal.NTAccount($ClientGroupED)

$IdentityReference = $NTAccount.Translate([System.Security.Principal.SecurityIdentifier])

$ActiveDirectoryRights = [System.DirectoryServices.ActiveDirectoryRights] "GenericAll"

$AccessControlType = [System.Security.AccessControl.AccessControlType] "Deny"

$Inherit = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "All"  #All, Children, Descendents, None, SelfAndChildren

$ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($IdentityReference,$ActiveDirectoryRights,$AccessControlType,$Inherit)

$ADSI.psbase.ObjectSecurity.SetAccessRule($ACE)

$ADSI.psbase.commitchanges()

I tried passing the alternate credentials using -Credential $Cred and also passed the -ArgumentList $Cred while calling New-Object neither works. Need some help in this issue.

JonC
  • 978
  • 2
  • 7
  • 28

2 Answers2

1

The only place where you're actually talking to AD is at $ADSI.psbase.commitchanges(). So the only place you need to set credentials is when you create $ADSI.

The [ADSI] type accelerator is just a shortcut to creating a DirectoryEntry object. DirectoryEntry does have a constructor that accepts credentials, but to use it, you can't use the type accelerator anymore. You'll need to use New-Object, like this:

$ADSI = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$OUPath", "username", "password")

Just replace username and password with credentials that have permission to do what you're doing.

If you want the script to call Get-Credential and use whatever credentials the user enters, then you can use the solution here.

A side note: you don't need to use psbase in the last two lines. You can if you want, but it makes no functional difference. You can do without:

$ADSI.ObjectSecurity.SetAccessRule($ACE)

$ADSI.CommitChanges()
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
1

You can also set the credentials directly on the ADSI object. I have tested this to set the terminal services properties for a user.

$ADSI = [ADSI]("LDAP://" + $userdn)
$ADSI.psbase.Username = $credential.username
$ADSI.psbase.Password = $credential.GetNetworkCredential().Password 

//get the value of a property
$output["property"] = $ADSI.psbase.InvokeGet("Property")

//set the value of a property
$ADSI.psbase.InvokeSet("Property", "your value")
$ADSI.CommitChanges()
myeongkil kim
  • 2,465
  • 4
  • 16
  • 22
Oana Rotar
  • 11
  • 2