Link to home
Start Free TrialLog in
Avatar of Ben Hart
Ben HartFlag for United States of America

asked on

Powershell Script Help request: If found, else

Script to create a new domain user.. I have a part that checks for the existence of an email address.

Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress}
	$found=Get-ADuser  -filter * -Properties ProxyAddresses|
     Where-Object{
        $_.proxyaddresses | 
             Where-Object{ $_ -eq $ProxyAddress }}

if($found){
	write-host "ProxyAddress Exists, Change username to something unique!"
get-aduser -filter * -properties $proxyaddress
pause 5
}
	else {
	write-host "ProxyAddress Not Found!"
Pause 5

}

Open in new window


If I input a proxyaddress that does not already exist I get the write-host saying "ProxyAddress Not Found".  However if it does exist then I get an error:

get-aduser : One or more properties are invalid.
Parameter name: jmanwell@domain.net
At D:\Users\bhart.DIFC\Dropbox\Scripts\Create_New_AD_user_O365.ps1:36 char:1
+ get-aduser -filter * -properties $proxyaddress
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser


I'd obviously like for this part to say the address already exists and re-prompt me to input a correct one.  Back in the day that'd be a goto line whatever, but I doubt that works in PS lol.
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ben Hart

ASKER

So this would replace the entire segment I listed originally?
Nevermind.. works like a champ by just replacing the part:

if($found){
	write-host "ProxyAddress Exists, Change username to something unique!"
get-aduser -filter * -properties $proxyaddress
pause 5
}
	else {
	write-host "ProxyAddress Not Found!"
Pause 5

}

Open in new window

Replace all posted content, please.
Really?  This is what I have now and it works like a champ:

Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress}
      $found=Get-ADuser  -filter * -Properties ProxyAddresses|
     Where-Object{
        $_.proxyaddresses |
             Where-Object{ $_ -eq $ProxyAddress }}

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."

I will comment out the top part that was in my original and give it a test.
And it still works.  interesting but thanks for letting me know.
With the partitially replaced code you are doing the AD query 3 times. Only once is sufficient :D.