In my last post I showed how after several steps we ran
(Get-WmiObject win32_groupuser -Filter $query).PartComponent
and got
\\PC\root\cimv2:Win32_UserAccount.Domain="PC",Name="Administrator" \\PC\root\cimv2:Win32_Group.Domain="Domain",Name="Desktop Admins" \\PC\root\cimv2:Win32_Group.Domain="Domain",Name="Domain Admins" \\PC\root\cimv2:Win32_UserAccount.Domain="Domain",Name="ME"
Now we’re going to clean this up into a format that is more readable. First let’s take that last command and assign it to a variable:
$list = (Get-WmiObject win32_groupuser -Filter $query).PartComponent
This variable, $list, is actually an array. As such we can now create a foreach loop and process each line. The first thing we’re going to do is isolate the domain portion out.
foreach ($l in $list) { $domain = $l.Substring($l.IndexOf("`"")+1) $domain = $domain.Substring(0,$domain.IndexOf("`"")) $domain | Out-Default }
So what we have done is get the domain out. Looking at the first line where the variable $domain is set we found the first case of the double quote character and removed everything to the left of it by first using the IndexOf method to find the position of the ” and then the Substring method to crop off the data to the left of it. By adding 1 to the IndexOf value we made sure to include the ” in the removed text. Note I had to use the sequence `” (NOT ‘ – ` which is the key to the left of the 1 key on a US keyboard) to be able to include the ” character in the search string. The next line involves finding the next ” and removing everything to the right of it. So our output from the loop is:
PC Domain Domain Domain
Now let’s add some code to get the user/group name.
foreach ($l in $list) { $domain = $l.Substring($l.IndexOf("`"")+1) $UG = $domain $domain = $domain.Substring(0,$domain.IndexOf("`"")) $UG = $UG.Substring($UG.IndexOf("`"")+1) $UG = $UG.Substring($UG.IndexOf("`"")+1) $UG = $UG.Substring(0,($UG.Length-1)) $domain + "\" + $UG | Out-Default }
We’ve added a new variable $UG. Our first step is to capture the portion of the string after the section to the first ” is stripped off – we need the value at the end. The next time we set $UG we are stripping everything up to and including the second ” in the original string. Then we repeat to the third ” in the original. Finally we strip off the the last “. Adding a “\” and the $UG value to our output gives us this:
PC\Administrator Domain\Desktop Admins Domain\Domain Admins Domain\ME
Next time I’ll go over building a report for this information so it can be handed off to auditors.