3

I am completely stuck! Hoping someone can help point out what I'm doing wrong. PS script below.

For testing I have 2 users in "newusers.csv" and the same 2 users in "currentmembers.csv". These are teh same file just renamed. Results of script are that the 2 users in "newusers.csv" are NOT members of "currentmembers.csv". This is obviously wrong but I can't figure out what is wrong with the script.

$list = Import-Csv newusers.csv
$members = Import-Csv currentmembers.csv

foreach ($UPN in $list) {
    If ($members-Contains $UPN.upn) {
       Write-Host $UPN.upn "is member"
   } Else {
       Write-Host $UPN.upn "is not a member"
    }}

Results user 1 is not a member user 2 is not a member

007
  • 31
  • 1

3 Answers3

1

Your $member should be an array of strings, not array of objects. Same thing as you are comparing $upn.UPN - the $upn is a object and you're accessing UPN member of it.

Hope that I explained this clearly

$members = Import-Csv currentmembers.csv | select -expandproperty ColumnName
mklement0
  • 382,024
  • 64
  • 607
  • 775
DNKO
  • 73
  • 1
  • 5
1

Your two Import-CSV calls are creating an array of objects, each containing two objects with 1 value (UPN). Your use of -contains will not work here as, you are not comparing directly to a string, more info here.

You have two options.

#1 you can use -in

foreach ($UPN in $list) {
    If ($UPN.upn -in $members.upn) {
       Write-Host $UPN "is member"
    } 
    Else {
       Write-Host $UPN "is not a member"
    }
}

#2 You can use -match

foreach ($UPN in $list) {
    If ($members -match $UPN.upn) {
       Write-Host $UPN.upn "is member"
    } 
    Else {
       Write-Host $UPN.upn "is not a member"
    }
}
Owain Esau
  • 1,876
  • 2
  • 21
  • 34
1

Completely agree with Owain's answer, but I got halfway through mine so I thought I'd finish it. You can try playing with sample data directly in PowerShell as follows, using ConvertFrom-Csv, which saves you editing files and then hopping back into PowerShell:

$list = @'
upn
user 1
user 2
user 7
user 99
'@ | ConvertFrom-Csv

$members = @'
upn
user 2
user 1
user 4
'@ | ConvertFrom-Csv

foreach ($UPN in $list) {
    If ($UPN.upn -in $members.upn) {
       Write-Host $UPN.upn "is member"
   } Else {
       Write-Host $UPN.upn "is not a member"
}}

As Owain said, you need to alter the comparison part to compare a string to an array.

mjsqu
  • 5,151
  • 1
  • 17
  • 21