Tuesday, September 27, 2011

Parsing Text with PowerShell

Lately I do a lot of things with PowerShell, but very little text parsing. I think it takes me longer to think of a best way to achieve what usually I'm searching for ... besides, I'm not that good at "Regular Expression". So that has been a discouraging factor when it comes to parsing text.  Anyway, but I've been playing with Split and Join  a little for fun and wanna show you something very simple.

So I used the dsget utility to lookup a Domain Group membership. The actual command will look something like this...

dsget group "CN=Domain Admins, dc=mydomain,dc=com" -members

In my current scenario, I don't want to sue any tools/method that will require RPC port (and I think the dsget utility strictly uses LDAP port 389).

So I ran into an issue with groups that are "Domain Local" type and contains Foreign Security Principals. Another words, when you do dsget against one of those groups contains users from trusted Domain, you see nothing but SID .. no friendly names. Arrgh!

So for that I need a function to convert the SID, but I had to first clean out other garbage from the dsget and only list the SID so I can later perform a foreach to convert to friendly names.

Anyway, so I performed the lookup against the group and got a output like this

"CN=S-1-5-21-10882098-2476436-466898754-546853, CN=ForeignSecurityPrincipals, DC=mydom, DC=com"
So I put above into a variable
$Users = dsget group "CN=Domain Admins, dc=mydomain,dc=com" -members

Now break it down ...
$getSID=$Users |where-object {$_ -match "CN=S"} |ForEach-Object {$_.Split("CN=,")} |Select-String -Pattern "S-*" |Where-Object {$_.Line -like "S-*"}

Now I get bunch of these

S-1-5-21-1099217021-36939962319-411451142-96491
S-1-5-21-1099217021-36939962319-411451142-90117
S-1-5-21-1099217021-36939962319-411451142-96129
S-1-5-21-1099217021-36939962319-411451142-96250
so I have the SID I wanted which I could convert by using a function like this

function Translate-SID
{
    param($sid)
    $ID = New-Object System.Security.Principal.SecurityIdentifier($sid)
    $User = $ID.Translate( [System.Security.Principal.NTAccount])
    $User.Value
}


and converting line by line like this

foreach ($uSID in $getSID){Translate-SID $uSID}

You can do the same as above by using other utilities such as netSH, wmic, and so on.  

1 comment:

  1. By the way, as you can see the ldap path, so for obvious reason, don't follow it word for word :)

    Domain Admins group usually a "Global Group" Type which cannot hold any Foreign Security Principals (users from a Trusted Domain), so you will have to perform the query against a group that is a "Domain Local" type group which will have users that shows up as unfriendly name under dsget.

    ReplyDelete