Powershell - Code help request

I have an existing posh script that's been working now I thought for a year.  However one step of it appears to be working but is not.. that's what Im wanting help with.

SO here's the script:

#Create-NewADUserO365.ps1
#3/3/15 Benjamin Hart, Unified Brands, Inc
#Created with Powershell ISE
#This powershell script will create a domain user object using a format of lastname, firstname, a SAM of first initial + last name
#It will also populate displayname, a default password, office and both proxyaddresses, the primary as used in your org and the 
#Dover required O365 one.  It will also verify the primary proxy address is not already used.
#With set-aduser you can alter almost any attribute of the user.

$theOU = read-host "Enter the OU name"
$Surname = read-Host "Enter the surname"
$GivenName = read-host "Enter first name"
$DisplayName = "$Surname, $GivenName"
$Password = "P@$$word1"
$name = $GivenName.substring(0,1)+$Surname
$proxyaddress = read-host "Enter the email address in full"


Import-Module activedirectory
# import-module servermanager



	#Edit the SearchBase to match your organization
	$myOU = Get-AdOrganizationalUnit -Filter "Name -eq '$theOU'" -Searchbase 'OU=People,DC=DIFC,DC=Root01,DC=org'
	

[b][u]while (Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress})
{
  $proxyaddress = read-host "$proxyaddress is already in use, please try another one"
}
Write-Host "$proxyaddress is not used yet."[/u][/b]


#Edit the below to match your domain(s)
$DoverProxyAddress = "$("smtp:")$($givenname.substring(0,1))$surname-$("unifiedbrands")-$("net")@dover.mail.onmicrosoft.com"
$Description = read-host "Enter persons description"
$jobtitle = read-host "Enter the Job Title"

#Edit the below to match your locations
$office = read-host "Enter the user's location, Michigan, Mississippi, Georgia, Oklahoma or Remote"

#Edit your locations if you choose to use this part
Switch ($Office)  {
    "Michigan" {
        $Street = "525 South Coldwater Rd."
        $City = "Weidman"
        $State = "Michigan"
        $Zip = "48898"
        $scriptpath = "\\domain\netlogon\milogin1.bat"
}
    "Mississippi"  {
        $Street = "1055 Mendell Davis Dr."
        $City = "Jackson"
        $State = "Mississippi"
        $Zip = "39272"
        $scriptpath = "\\domain\netlogon\adlogin.bat"
        }
    "Oklahoma"  {
        $Street = "4650 54th Street Maip Building 601"
        $City = "Pryor"
        $State = "Oklahoma"
        $Zip = "74361"
        $scriptpath = "\\domain\netlogon\oklogin.bat"
        }
    "Georgia"  {
        $Street = "2016 Gees Mill Rd. NE"
        $City = "Conyers"
        $State = "Georgia"
        $Zip = "30013"
}
}

$department = read-host "Enter the users Department"

New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $DisplayName -Surname $Surname -givenname $givenname -AccountPassword (ConvertTo-SecureString password -AsPlainText -force) -enabled:$false
set-aduser $name -emailaddress $proxyaddress -Description $Description -Title $jobtitle -Office $office -StreetAddress $Street -city $city -state $state -PostalCode $zip -UserPrincipalName $proxyaddress -ScriptPath $scriptpath -Department $department -Company "Unified Brands, Inc" -Country "US"

set-aduser $name -add @{proxyaddresses = "$("SMTP:")$proxyaddress"}
set-aduser $name -add @{ProxyAddresses = "$doverproxyaddress"}

 	
get-aduser $name 


pause

Open in new window


The bold and underlined section is what is not working.  It should be checking to see if an smtp address is already in use, if so not letting me continue on, however yesterday was the first tie I had cause to create a domain user who would match an existing smtp address, but the script told me everything was fine and let me continue on.  It wasn't until the end where the New-Aduser came into play where it actually generated an error.
LVL 14
Ben HartAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jeremy WeisingerSenior Network Consultant / EngineerCommented:
One thing is that you're comparing proxy addresses and not samaccount, UPN, or DN. The New-ADUser is failing because of another conflict, not the proxy address. Also, you're only checking email addresses on user accounts. Do any other objects have email addresses that need to be checked? (not that this would cause an error when creating the user)

Can you post the error?
0
Ben HartAuthor Commented:
That's not correct Jeremy.. the script creates the user just fine as I used it this morning to create a different new user account.  The one in question didn't fail on creation becaue of a matching proxyaddress but because of a username conflict.  Msmith already exists, but that underlined section of code is supposed to let me know he already exists and not let me create another Msmith.
Of course I know Im missing code to actually halt the script.. but my idea back then was if it tells me $proxyaddress Already Exists then I can stop the script from running and change the values I enter.
0
Ben HartAuthor Commented:
Here's what happenes on the conflict user.

Enter the OU name: Engineering
Enter the surname: Smith
Enter first name: Michelle
Enter the email address in full: msmith@unifiedbrands.net
msmith@unifiedbrands.net is not used yet.
Enter persons description: Design Engineer
Enter the Job Title: Design Engineer
Enter the user's location, Michigan, Mississippi, Georgia, Oklahoma or Remote: M
ichigan
Enter the users Department: Engineering

set-aduser : Insufficient access rights to perform the operation
At D:\Users\bhart.DIFC\Dropbox\Scripts\Create-NewADUserO365.ps1:76 char:1
+ set-aduser $name -emailaddress $proxyaddress -Description $Description
-Title $j ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : NotSpecified: (MSmith:ADUser) [Set-ADUser], ADEx
   ception
    + FullyQualifiedErrorId : ActiveDirectoryServer:8344,Microsoft.ActiveDirec
   tory.Management.Commands.SetADUser



DistinguishedName : CN=Smith\, Mike,OU=Technical
                    Services,OU=Employees,OU=People,DC=DIFC,DC=root01,DC=org
Enabled           : True
GivenName         : Mike
Name              : Smith, Mike
ObjectClass       : user
ObjectGUID        : 07e0e821-15df-42b4-b556-65b812b1cbd6
SamAccountName    : msmith
SID               : S-1-5-21-3552876221-1377390008-3480628798-6865
Surname           : Smith
UserPrincipalName : msmith@unifiedbrands.net

Press Enter to continue...:

Open in new window


I assume it says I don't have sufficient access rights to create a new domain user account with an identical upn to an existing one.
0
What were the top attacks of Q1 2018?

The Threat Lab team analyzes data from WatchGuard’s Firebox Feed, internal and partner threat intelligence, and a research honeynet, to provide insightful analysis about the top threats on the Internet. Check out our Q1 2018 report for smart, practical security advice today!

Jeremy WeisingerSenior Network Consultant / EngineerCommented:
That's not correct Jeremy.. the script creates the user just fine as I used it this morning to create a different new user account.
I never said it wouldn't.

The one in question didn't fail on creation becaue of a matching proxyaddress but because of a username conflict.
This is exactly my point. The proxyaddress is not a good check because you didn't check to see if the SAMAccountName (username), UPN, or DN conflicts. Those have to be unique and the proxy address check won't tell you that.
0
Ben HartAuthor Commented:
That's my main goal though.. I must not have any identical proxyaddresses in our O365 tenant.  So checking the UPN really doesn't help me unless I check both the UPN and the proxyaddress.  Honestly I'd like for it just to say "Hey there's an existing proxyaddress with this value.. change it"  In changing the proxyaddress in our domain means also changing the UPN as well.
0
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
Insufficient access rights to perform the operation
This does mean there's a permissions issue. If it was a conflict you would get:
The specified account already exists
0
Ben HartAuthor Commented:
OK IDK WTH is going on here lately but my account has delegated rights to the People ou to create user accounts.  But I just ran it as domain admin and yes I get the account already exists.  Like I said IDk what's going on here because I literally created a new account this same way I've been using for a year now.  UGh.

So yeah back to my original question.. The script is still ignoring the fact that this proxyaddress already exists.

PS C:\> d:
PS D:\users\bhart.difc\desktop> cd ..
PS D:\users\bhart.difc> cd dropbox
PS D:\users\bhart.difc\dropbox> cd scripts
PS D:\users\bhart.difc\dropbox\scripts> .\Create_New_AD_user_O365.ps1
Enter the OU name: Engineering
Enter the surname: Smith
Enter first name: Michelle
Enter the proxy address in full: msmith@unifiedbrands.net
msmith@unifiedbrands.net is not used yet.
Enter persons description: Design Engineer
Enter the Job Title: Design Engineer
Enter the user's location, Michigan, Mississippi, Georgia, Oklahoma or Remote: Michigan
Enter the users Department: Engineering
New-ADUser : The specified account already exists
At D:\users\bhart.difc\dropbox\scripts\Create_New_AD_user_O365.ps1:77 char:1
+ New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $Di ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (CN=Smith\, Mich...C=root01,DC=org:String) [New-ADUser], ADIdentityAlrea
   dyExistsException
    + FullyQualifiedErrorId : ActiveDirectoryServer:1316,Microsoft.ActiveDirectory.Management.Commands.NewADUser



DistinguishedName : CN=Smith\, Mike,OU=Technical Services,OU=Employees,OU=People,DC=DIFC,DC=root01,DC=org
Enabled           : True
GivenName         : Mike
Name              : Smith, Mike
ObjectClass       : user
ObjectGUID        : 07e0e821-15df-42b4-b556-65b812b1cbd6
SamAccountName    : msmith
SID               : S-1-5-21-3552876221-1377390008-3480628798-6865
Surname           : Smith
UserPrincipalName : msmith@unifiedbrands.net

Open in new window

0
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
OK, maybe this.

function Gather-UniqueInfo {
    $Surname = read-Host "Enter the surname"
    $GivenName = read-host "Enter first name"
    $DisplayName = "$Surname, $GivenName"
    $proxyaddress = read-host "Enter the email address in full"
    $name = $GivenName.substring(0,1)+$Surname
    If(Get-ADUser -Filter {userprincipalname -eq $proxyaddress}){
        Write-Host "$proxyaddress already exists. Please enter another address"
        Gather-UniqueInfo
        }
    }


Gather-UniqueInfo
$theOU = read-host "Enter the OU name"
$Password = 'P@$$word1'


Import-Module activedirectory
# import-module servermanager



	#Edit the SearchBase to match your organization
	$myOU = Get-AdOrganizationalUnit -Filter "Name -eq '$theOU'" -Searchbase 'OU=People,DC=DIFC,DC=Root01,DC=org'
	

[b][u]while (Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress})
{
  $proxyaddress = read-host "$proxyaddress is already in use, please try another one"
}
Write-Host "$proxyaddress is not used yet."[/u][/b]


#Edit the below to match your domain(s)
$DoverProxyAddress = "$("smtp:")$($givenname.substring(0,1))$surname-$("unifiedbrands")-$("net")@dover.mail.onmicrosoft.com"
$Description = read-host "Enter persons description"
$jobtitle = read-host "Enter the Job Title"

#Edit the below to match your locations
$office = read-host "Enter the user's location, Michigan, Mississippi, Georgia, Oklahoma or Remote"

#Edit your locations if you choose to use this part
Switch ($Office)  {
    "Michigan" {
        $Street = "525 South Coldwater Rd."
        $City = "Weidman"
        $State = "Michigan"
        $Zip = "48898"
        $scriptpath = "\\domain\netlogon\milogin1.bat"
}
    "Mississippi"  {
        $Street = "1055 Mendell Davis Dr."
        $City = "Jackson"
        $State = "Mississippi"
        $Zip = "39272"
        $scriptpath = "\\domain\netlogon\adlogin.bat"
        }
    "Oklahoma"  {
        $Street = "4650 54th Street Maip Building 601"
        $City = "Pryor"
        $State = "Oklahoma"
        $Zip = "74361"
        $scriptpath = "\\domain\netlogon\oklogin.bat"
        }
    "Georgia"  {
        $Street = "2016 Gees Mill Rd. NE"
        $City = "Conyers"
        $State = "Georgia"
        $Zip = "30013"
}
}

$department = read-host "Enter the users Department"

New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $DisplayName -Surname $Surname -givenname $givenname -AccountPassword (ConvertTo-SecureString password -AsPlainText -force) -enabled:$false
set-aduser $name -emailaddress $proxyaddress -Description $Description -Title $jobtitle -Office $office -StreetAddress $Street -city $city -state $state -PostalCode $zip -UserPrincipalName $proxyaddress -ScriptPath $scriptpath -Department $department -Company "Unified Brands, Inc" -Country "US"

set-aduser $name -add @{proxyaddresses = "$("SMTP:")$proxyaddress"}
set-aduser $name -add @{ProxyAddresses = "$doverproxyaddress"}

 	
get-aduser $name 


pause

Open in new window

0
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
Oops, forgot to clean up somethings:
function Gather-UniqueInfo {
    $Surname = read-Host "Enter the surname"
    $GivenName = read-host "Enter first name"
    $DisplayName = "$Surname, $GivenName"
    $proxyaddress = read-host "Enter the email address in full"
    $name = $GivenName.substring(0,1)+$Surname
    If(Get-ADUser -Filter {userprincipalname -eq $proxyaddress}){
        Write-Host "$proxyaddress already exists. Please enter different info"
        Gather-UniqueInfo
        }
    }


Gather-UniqueInfo
$theOU = read-host "Enter the OU name"
$Password = 'P@$$word1'


Import-Module activedirectory
# import-module servermanager



	#Edit the SearchBase to match your organization
	$myOU = Get-AdOrganizationalUnit -Filter "Name -eq '$theOU'" -Searchbase 'OU=People,DC=DIFC,DC=Root01,DC=org'
	


#Edit the below to match your domain(s)
$DoverProxyAddress = "$("smtp:")$($givenname.substring(0,1))$surname-$("unifiedbrands")-$("net")@dover.mail.onmicrosoft.com"
$Description = read-host "Enter persons description"
$jobtitle = read-host "Enter the Job Title"

#Edit the below to match your locations
$office = read-host "Enter the user's location, Michigan, Mississippi, Georgia, Oklahoma or Remote"

#Edit your locations if you choose to use this part
Switch ($Office)  {
    "Michigan" {
        $Street = "525 South Coldwater Rd."
        $City = "Weidman"
        $State = "Michigan"
        $Zip = "48898"
        $scriptpath = "\\domain\netlogon\milogin1.bat"
}
    "Mississippi"  {
        $Street = "1055 Mendell Davis Dr."
        $City = "Jackson"
        $State = "Mississippi"
        $Zip = "39272"
        $scriptpath = "\\domain\netlogon\adlogin.bat"
        }
    "Oklahoma"  {
        $Street = "4650 54th Street Maip Building 601"
        $City = "Pryor"
        $State = "Oklahoma"
        $Zip = "74361"
        $scriptpath = "\\domain\netlogon\oklogin.bat"
        }
    "Georgia"  {
        $Street = "2016 Gees Mill Rd. NE"
        $City = "Conyers"
        $State = "Georgia"
        $Zip = "30013"
}
}

$department = read-host "Enter the users Department"

New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $DisplayName -Surname $Surname -givenname $givenname -AccountPassword (ConvertTo-SecureString password -AsPlainText -force) -enabled:$false
set-aduser $name -emailaddress $proxyaddress -Description $Description -Title $jobtitle -Office $office -StreetAddress $Street -city $city -state $state -PostalCode $zip -UserPrincipalName $proxyaddress -ScriptPath $scriptpath -Department $department -Company "Unified Brands, Inc" -Country "US"

set-aduser $name -add @{proxyaddresses = "$("SMTP:")$proxyaddress"}
set-aduser $name -add @{ProxyAddresses = "$doverproxyaddress"}

 	
get-aduser $name 


pause

Open in new window

0
footechCommented:
The issue with your check of the proxyAddresses is that those are not exactly in an email address format like "user@domain.com".  Instead they are like "SMTP:user@domain.com".  So your -contains comparison is never going to match.  You could try this.
Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains "smtp:$proxyaddress"}

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ben HartAuthor Commented:
Sweet.. both ideas work.  Thanks a bunch fellas.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.