Retrieving an RDN from an Active Directory User Object - powershell

Is it possible to retrieve the RDN of a user object in Active Directory with the attribute intact.
I've done a lot of reading on this and found that an AD user object stores the RDN in an property called "name". Supposedly the value of the name (rdn) property should be something like name = "cn=Smith, Joe". The cn attribute is part of what should be returned. However whenever I retrieve the name property of an object the "cn=" always seems to be missing. For instance
$foo = get-aduser -filter 'Name -like "Smith, Joe"'
$foo.name
will return "Smith, Joe" not "cn=Smith, Joe". Is there someway to query and get the full RDN to return?

An alternative, is to grab the full DN of the object, split the DN, and display the first element in the resulting array, which will be the RDN, either CN= or otherwise, object dependent
$((foo.distinguishedname).split(","))[0]

Not really an answer but informations :
First the attributeId of the RDN attribute is fixed by the schema :
On the RDN point of view Active-Directory inherit from X500 standard. That is to say that you don't choose the attribute you want to create the RDN (in other LDAP directories you can). In Active-Directory the RDN attribute is given in the class schema by rDNAttID, it specifies the attributeId of the RDN attribute. If you look the schema for the class user it's CN.
So you can use :
"CN=$((get-aduser 'Smith, Joe').Name)"
Second do the following experiment :
In an OU create a user called 'Mananegement' you have the following DN CN=MAnagement,OU=MyOU,... now try to create, in the same OU, an OU named 'Mananegement' it should create an object with the following DN OU=MAnagement,OU=MyOU,..., but you receive an error. This error makes me beleive that somehow Active-Directory consider 'Mananegement' as the RDN and not 'CN=Mananegement' like others directories.

$current.Substring($current.IndexOf('OU='))

Related

Powershell to get an OU's ACL-Security Auditing policy and its enabled entries

I am trying to get a report out of Powershell and AD that will show me the list of items on this property page from Active Directory –
From ADUC, right click your Root Domain OU -> properties->Security tab->Advanced->Auditing-> Select/Open one of the auditing entries. It will look Something like this:
On that page you will see the Principal, Type, and Applies To fields at the top and on the bottom section, the Permissions and Properties being audited, checked or unchecked.
I want to list those items and their values via Powershell.
I get to that Auditing page by doing this:
AD:\> $acl = get-acl 'DC=domain,DC=company,DC=com' -Audit
AD:\> $acl.Audit
Then single out one of the entries:
AD:\> $acl.Audit[0]
ActiveDirectoryRights : GenericAll
InheritanceType : All
ObjectType : 00000000-0000-0000-0000-000000000000
InheritedObjectType : 00000000-0000-0000-0000-000000000000
ObjectFlags : None
AuditFlags : Success, Failure
IdentityReference : Everyone
IsInherited : False
InheritanceFlags : ContainerInherit
PropagationFlags : None
But that’s as far as I can get being a n00b. The only thing Ive been able to extract out of that list is the value itself and im not even sure which item if any of these might contain the items/values I want. Am I even in the right place?
Thanks in advance,
Richard
So here's the thing, the PowerShell ACL is only going to show you some of the things in that list. Here's what you can do to figure that bit out:
From what you have it looks like the ActiveDirectoryRights property is what's going to tell you what rights the given rule is affecting. Let's look at what that property's type is to see if we can get a list of what it considers to be valid values. We can run the .GetType() method on the property to see that it is the type [ActiveDirectoryRights], but that's not sufficient to get what we want. We'll want the full name, which we can get like this:
$acl.Audit[0].ActiveDirectoryRights.GetType()|Format-List
So the important things here are the BaseType and FullName properties. The BaseType is System.Enum, and the FullName is System.DirectoryServices.ActiveDirectoryRights. From that we can use the [Enum] base type to get the names associated with our type.
[enum]::GetNames([System.DirectoryServices.ActiveDirectoryRights])
That gets us this list of values:
CreateChild
DeleteChild
ListChildren
Self
ReadProperty
WriteProperty
DeleteTree
ListObject
ExtendedRight
Delete
ReadControl
GenericExecute
GenericWrite
GenericRead
WriteDacl
WriteOwner
GenericAll
Synchronize
AccessSystemSecurity
These can also be found here. That site also tells you what each means, and for things like GenericAll what other rights that groups together.
This is the info you're going to get from PowerShell, so if that's sufficient then awesome, you've got what you're looking for. If you expect to get all of the fine grained permissions for each object type listed I don't think you're going to want to use PowerShell for that. Yes, they're listed, but you're going to have to translate object type GUIDs. The only way I know of to do that is query AD for all of your classes that have a schemaIDGUID, and basically build a hashtable out of them that you can reference later when you're looking up all of these accesses. This bit you only have to do once, then just reference $GUIDHT when you need to lookup a GUID.
For example:
#Connect to ADDS and get a list of all objects with a schemaIDGUID
$root = Get-ADRootDSE
$schemaContext = $root.schemaNamingContext
$schemaObjects = Get-ADObject -SearchBase $schemaContext -Filter 'schemaIDGUID -like "*"' -Properties 'Name', 'schemaIDGUID', 'objectClass'
#Create hashtable with generic 'All' entry for all zero guids
$GUIDHT = #{[System.Guid]'00000000-0000-0000-0000-000000000000'=#{Name='All'}}
#Populate the hashtable with all of the GUIDs we found in AD
$schemaObjects|ForEach-Object{ $GUIDHT[$_.ObjectGUID]=$_ }
#Find the friendly name for a specific audit rule listing
$GUIDHT[$acl.Audit[0].ObjectType].Name
Then things start to get confusing for PropagationFlags vs InheritanceFlags. InheritanceFlags determine what kind of objects can inherit the rule. PropagationFlags determine if the rule applies to only the object, only the children of the object, or both.

How to create AD Object "RID Set" in PowerShell?

I have a question. In AD structure I find AD object RID Set which placed as child of ADComputer object.
If I create new ADComputer object, how can I create RID set object in Powershell? Is it possible?
Is it possible?
No
The RID-Set class is marked System-Only, meaning that only a DSA (iow. the DC itself) can create such an object.
You can verify this by looking at the schema with Get-ADObject:
Get-ADObject "CN=RID-Set,$((Get-ADRootDSE).schemaNamingContext)" -Properties systemOnly
You'll find that the systemOnly attribute is set to $true

ADSI Search for DistinguishedName of the primary group based on primarygroupid

Because we don't have the active directory module available on all our systems we're using ADSI instead. The following code retrieves a user object from AD by using the AdsiSearcher:
$ADUser = ([AdsiSearcher]"(samaccountname=$SamAccountName)").FindOne()
This results in finding the property primarygroupid which represents the domain primary group for user, usually number 513. When we have this number we would like to find the distinguishedName of the group. However, the code below does that just fine I was wondering if there is a better filter that can be used instead of filtering after the FindAll() method?
$searcher = [adsisearcher]'objectclass=group'
$searcher.PropertiesToLoad.Add('primarygrouptoken')
$searcher.PropertiesToLoad.Add('distinguishedName')
$searcher.FindAll() |
Where-Object { $_.Properties.primarygrouptoken -eq 513}
Something like this would be great but it's not possible:
([adsisearcher]”(&(objectCategory=group)(primaryGroupid=513))”).FindOne()
The primaryGroupToken is a constructed attribute, meaning that it's not actually materialized in the database, and can't be filtered using LDAP.
In order to build an equivalent filter we'll need to look at how it is constructed - and the primary group token in Active Directory is always the same as the group's RID part (the relative identifier) of the objectSid attribute.
So, if we want to search by it, we can simply filter by objectSid instead:
# Obtain domain SID
$dncDN = ([adsi]"LDAP://RootDSE").defaultNamingContext
$dnc = [adsi]"LDAP://$dncDN"
$domainSID = [System.Security.Principal.SecurityIdentifier]::new($dnc.objectSid.Value, 0)
# Set the group ID we're looking for
$RID = 513
# Search for group by objectSid value:
([adsisearcher]"(&(objectCategory=group)(objectSid=${domainSID}-${RID}))").FindOne()

Powershell enumerate properties of properties

I have a commandlet that gathers information from a device register:
PS C:\windows\system32> Get-PSDevice serverA
HostName: ServerA
OOB:
Criticality: Normal
IsVirtual: True
etc
Some of these have an array of 'sub properties' inside, for example:
Cluster : #{Url=https://ps-apps.com/DeviceRegister/api/Clusters/62; VCenterUrl=https://ps-apps.com/DeviceRegister/api/VCenters/2; ClusterId=62; VCenterId=2; Name=Vcenter 1 ABC Prod;
DataCenterUrl=https://ps-apps.com/DeviceRegister/api/DataCenters/3; DataCenter=; IsValidated=True; IsExceptionCluster=False; SupportsProdWorkloads=False; SupportsNonProdWorkloads=False; SupportsSqlWorkloads=False;
ManagedByabc=False}
I can get whatever property within the aray I want using something like:
(Get-PSDevice ServerA).cluster.name
I'm trying to determine a way to enumerate all of the sub properties using a foreach type statement to populate a value.
What would be the best way to achieve this?
Every object in PowerShell has a hidden .PSObject property which tells you things about the object. One of its properties is a .Properties property (as PetSerAl points out, it's not a property but in fact a MemberSet, though you access it with property semantics).
(Get-PSDevice ServerA).cluster.PSObject.Properties
That would return [PSProperty] objects that show you the information about the properties (the name, value, type, whether it's gettable and settable, etc.).

How to filter Win32_UserAccount results by OU

In PowerShell, I already know how to use DirectoryEntry and DirectorySearcher to get a list of users in a certain OU. The results of this method are mostly what I am looking for in AD, but it seems easier to get the same information by using a WMI query Win32_UserAccount. I like the properties of this class better and the SID is already in the correct string format (in the first method it needs to be converted from a hex byte array to string).
The problem I have with using Win32_UserAccount is that I cannot find a way to filter it by an OU. I can successfully filter by domain and name, and have tried several guesses with WQL, but can't seem to find any syntax for an OU filter. Most of my attempts result in "Invalid query." The following is an example of a query that works:
$user = gwmi Win32_UserAccount -filter "name='somebody' AND domain='mydomain'"
If there is no way to filter this by OU then I will go back to using the DirectoryEntry/DirectorySearcher.
Given that there are no LDAP related properties for the Win32_Account class I think you're out of luck unfortunately.
You could of course use this to get the SID in the format you want in addition to the directory searching to get the LDAP related data.
Are you familiar with the free AD cmdlets from Quest?
http://www.quest.com/powershell/activeroles-server.aspx
You can filter users based on OU and get the SID in various formats:
PS> Get-QADUser SizeLimit 0 -SearchRoot <OU_DistinguishedName>' | fl *sid*
objectSid : 0105000000000005150000006753F33372134F3FF673476FF4023001
Sid : S-1-5-21-54781788-1045369324-1866953526-501
(...)