0

So basically I'm trying to return a list of accounts that doesn't match the ones in my whitelist.

And I'm doing so this way.

$UserList = Get-ADUser -Filter * -Server $domain | select -Property Name, samAccountName
$checkUsers = $UserList | Select-String -pattern $whitelist -notMatch

Now $checkUsers stores the values as (hashtables from what I can understand) returned from Select-String as such.

@{Name=user1; samAccountName=user1}
@{Name=user2; samAccountName=user2}
@{Name=user3; samAccountName=user3}

I've tried so many things to bored you with the details so I'll just make it short, I'll get straight to the point, I'm losing my sanity at this point...

How can turn this into an object so I can: As example.

ForEach ($user in $myNewObject) { Write-Host $user.Name }

If I create a hashtable myself and store some values in it, I can access the no problem but when its returned from the output of Select-String, I can' do anything with it...

Steven
  • 6,817
  • 1
  • 14
  • 14
Archangel
  • 13
  • 3

1 Answers1

3

Select-String is meant to be used on strings, not objects. :)

Lets say we have a whitelist of SamAccountNames like so

$whiteList = @('User1', 'User3')

and we have some users

$UserList


Name        SamAccountName
----        --------------
First User  User1
Second User User2
Third User  User3

We could get back the accounts that are not in our whitelist by doing the following with Where-Object

$UserList | Where-Object SamAccountName -notin $whitelist
# OR
# $UserList | Where-Object -FilterScript { $_.SamAccountName -notin $whitelist }

Output

Name        SamAccountName
----        --------------
Second User User2

Turning hashtable into objects

Just prefix your hashtable with the [PSCustomObject] type accelerator.

[PSCustomObject]@{Name='user1'; samAccountName='user1'}

Name  samAccountName
----  --------------
user1 user1

same if you have a hashtable saved in a variable

$hashUser = @{Name='user1'; samAccountName='user1'}
[PSCustomObject]$hashUser

samAccountName Name
-------------- ----
user1          user1
Steven
  • 6,817
  • 1
  • 14
  • 14
Daniel
  • 4,792
  • 2
  • 7
  • 20