I am trying to get the CN
and MemberOf
attributes from Get-ADGroup
and I am having an issue trimming the unneeded info from the MemberOf
property.
The code I am working with that gives me the results is as follows:
Get-ADGroup -searchbase "OU=TargetOU,....." -filter * -properties * | select CN, Memberof | Format-List
It gives me the following results:
CN : GroupName
Memberof : {CN=CN1blah,OU=OUblah,OU=OUblah,OU=OUblah,OU=OUblah,DC=DCBlah,DC=DCBlah,DC=DCBlah,DC=DCBlah,DC=DCBlah,CN=CN2blah,OU=OUblah,OU=OUblah,OU=OUblah,OU=OUblah,DC=DCBlah,DC=DCBlah,DC=DCBlah,DC=DCBlah,DC=DCBlah,CN=CN3blah,OU=OUblah,OU=OUblah,OU=OUblah,OU=OUblah,DC=DCBlah,DC=DCBlah,DC=DCBlah,DC=DCBlah,DC=DCBlah}
What I am looking for is this:
CN : GroupName
Memberof : CN1blah,CN2blah,CN3blah
So I am trying to Trim MemberOf
result down until only the CN1blah,CN2blah,CN3blah
is left
I tried adding a split and substring to the MemberOf
(see code below)and it produces an error
Get-ADGroup -searchbase "OU=TargetOU,....." -filter * -properties * | select CN, Memberof.split(',')[0].Substring(3) | Format-List
Error is as follows:
Method invocation failed because [System.Char] does not contain a method named 'Substring'.
At line:1 char:1
+ get-adgroup -searchbase "OU=OUblah,OU=OUblah,OU=OUblah,OU=OUblah ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
I figure its something simple I am missing or I am going about it the wrong way.
Can anyone help me figure out how to get the results I am looking for?
You'll need to use a calculated property for the memberOf
property:
Get-ADGroup -SearchBase 'OU=TargetOU,.....' -Filter * -Properties cn, memberof |
Select-Object CN, @{ N='MemberOf'; E= { $_.Memberof -replace '^CN=|(?<!\\),.+' }} |
Format-List
The replacement pattern will remove CN=
from the start of the string and then everything after the first ,
that is not preceded by \
.
The current expression will also result in an array, if you want to convert that array into a string you should also combine it with a -join
:
E={ $_.Memberof -replace '^CN=|(?<!\\),.+' -join ',' }