phoenix79
phoenix79

Reputation: 15

powershell if statement not executing

I am trying to write a Powershell script to automate AD user creation. We are a mixed Linux/Windows environment and use a text (now CSV) file to keep track of old linux UID #'s and usernames so they don't accidentally get re-used. I'm trying to get my script to parse the file but I can't seem to get the comparison to work.

$sam = $GivenName.substring(0,1).ToLower() + $lastname.ToLower()
$usernames=Import-csv "uid.csv" 
ForEach($users in $usernames){
if($usernames.username -contains $sam){$uid = $true}
}

I've used several different ways that I've found from around the web to read the data into an array from the file but the problem seems to be that no matter what, it never sets $uid = $true and I have no idea why.

Edit: I changed the if statement to this:

if($users.username -contains $sam){$uid = $true}

and it worked. Thanks for the help!

To clear up some confusion, the $GivenName and $lastname are input by the user and I am only looking for an exact match since I'm trying to avoid re-used usernames. Also, changing the -contains to -eq works as well. I've been fighting this for WAY too long and if you couldn't tell I'm a bit of a Powershell noob.

Upvotes: 0

Views: 178

Answers (2)

Adi Inbar
Adi Inbar

Reputation: 12323

It's a little unclear from the information you've provided, but here's what I think is the problem: Since $usernames comes from a CSV file, the $usernames.username is a string. The -contains operator is used on collections (such as arrays), and will only work if there's an exact match (and if you're looking for exact matches, you should use -eq, but I'm assuming that's not what you want). Use -match instead. Also, you're setting $users to each record in the CSV, so it should be $users.username. Change the if statement to this:

if ($users.username -match $sam) {
  $uid = $true
}

Upvotes: 1

manojlds
manojlds

Reputation: 301037

The looping variable that you are using in your loop in $users, but within the loop you use $usernames. You probably wanted to use $users.username within the if statement

Upvotes: 1

Related Questions