Tom Crawshaw
Tom Crawshaw

Reputation: 11

Getting Local user objects and comparing them to a known good string?

Hi im currently working on a script to monitor back to an RMM tool, seem to be having issues converting my objects to match a "known string" inside my script.

ideally i'd like to poll the local computers local admin group then inline compare that with a string i've predefined, i was hoping to get the value, then just write a multi-lined string to match, then do some if statements to compare the 2.

$test3 = Get-LocalGroupMember -SID "S-1-5-32-544" | select -ExpandProperty Name | out-string

$test =@" 
PC\Administrator
PC\test
"@

this is a little snippet, so the first one pulls the local ad group then saves it to a varible, and $test is my defined variable.

Both appear identical when outputted to console.

thanks so much in advance.

Upvotes: 1

Views: 647

Answers (2)

Theo
Theo

Reputation: 61208

Instead of a predefined multiline string, Use either a string array or a hashtable to compare against. The way you try to do it can fail the comparison simply because the items returned can be in a different order as in your predefined string.

Option 1: use an array

$testUsers = 'PC\Administrator', 'PC\test'
# this gets the users that are mentioned in the $testUsers array.
# if you want the opposite (users in the group, but NOT in the $testUsers array),
# change '-contains' into '-notcontains'
(Get-LocalGroupMember -SID "S-1-5-32-544").Name | Where-Object { $testUsers -contains $_ }

Option 2: use a Hashtable (a bit more work to set up, but extremely fast)

$testusers = @{
    'PC\Administrator' = $true  # the Values will not be used, so anything can go in here
    'PC\test'          = $true
 }
# this gets the users that are mentioned in the $testUsers Hashtable.
# if you want the opposite (users in the group, but NOT in the $testUsers Hashtable),
# change '$testUsers.ContainsKey($_)' into '!$testUsers.ContainsKey($_)'
(Get-LocalGroupMember -SID "S-1-5-32-544").Name | Where-Object { $testUsers.ContainsKey($_) }

Upvotes: 1

Architect Jamie
Architect Jamie

Reputation: 2599

It's a bug in Windows where orphaned SIDs are left in the group. Try this instead:

$adminGroup = [ADSI]::new("WinNT://$env:COMPUTERNAME/$((Get-LocalGroup -SID S-1-5-32-544).Name)")
$adminGroupMembers = $adminGroup.Invoke('Members') |% {([ADSI]$_).Path.Replace('WinNT://', '')}
$adminGroupMembers | Out-String

You'll need to manipulate the output as required.

Upvotes: 0

Related Questions