Powershell smtp if / elseif / else optimize and help with completion

Dear experts,

can anybody help and optimize with this smtp creation script below. $newsmtp has to add as primary
smtp and $newsmtp2 has to set as secondary smtp. The output of both has to be written to smtp.csv
gal.com, test.com,dal.com has to add as secondary smtp for specified company only

Appreciate for your help. Thanks in advance. mandy_


$data = $null
$data = @{}
Select-String c:\hash2.txt -Pattern "([a-z]+).+?=.+?([a-z.]+)" |
ForEach { $_.matches} |
ForEach { $tokens = @($_.groups[1].value,$_.groups[2].value); $data.Add($tokens[0],$tokens[1])}
 #$data
Import-Csv c:\1.csv | ForEach `
{

$_.name.ToLower() -match "^(?<last>[a-z -]+),( (?<middle>[a-z]+))? (?<first>[a-z-]+)( (?<code>[a-z0-9()]+))?$" | Out-Null
$first = $matches["first"] -replace "[^a-z]","."
$middle = $matches["middle"] -replace "[^a-z]","."
$middle2 = $matches["middle"] -replace "[^a-z]","."
$last = $matches["last"] -replace "[^a-z]","."
$code = $matches["code"] -replace "[()]"
$company = $data[$_.company]
If ($middle)
{ $middle = "." + $middle }
If ($code)
{ $code = "." + $code }
    
    
If ($_.UserId -like "z1*" -or $_.UserId -like "z8*" -and $_.Company -like "TAL*") {
$newSMTP = "{0}.{1}.{2}@{3}" -f $first,$last,"sp",$company 
$mbox = Get-Mailbox $_.UserID
$mbox
}
ElseIf ($_.Company -like "GAL*") {
$newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"gal.com" 
$mbox = Get-Mailbox $_.UserID
$mbox
}
ElseIf ($_.Company -like "GAL*") {
$newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"test.com" 
$mbox = Get-Mailbox $_.UserID
$mbox
}
ElseIf ($_.Company -like "DAL*") {
$newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"dal.com" 
$mbox = Get-Mailbox $_.UserID
$mbox
}   
Else {
$newSMTP = "{0}{1}{2}.{3}{4}@{5}" -f $first,$middle,$middle2,$last,$code,$company
$mbox = Get-Mailbox $_.UserID
$mbox
}   
    
If ($mbox.PrimarySMTPAddress -ne $newSMTP)
{
Write-Host  -ForegroundColor Green "Setting primary SMTP $newsmtp address for $mbox"
$newsmtp | out-file -filepath c:\smtp4.csv -append
set-mailbox -identity $_.UserID -PrimarySmtpAddress $newsmtp -EmailAddressPolicyEnabled $false -SingleItemRecoveryEnabled $true
Set-Mailbox -Identity $User.userid -EmailAddresses $newsmtp2
$newsmtp2 | out-file -filepath c:\smtp4.csv -append
} else {
Write-Host -ForegroundColor red -backgroundcolor yellow "$mbox has an SMTP-Address already exists in system"
}
}

Open in new window

LVL 2
Mandy_Asked:
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.

QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Before I start applying the desired changes, here is the revised code doing the same as you've posted:
$data = @{}
Select-String c:\hash2.txt -Pattern "([a-z]+).+?=.+?([a-z.]+)" |
  Select -Expand matches |
  ForEach { $data += @{ $_.groups[1].value = $_.groups[2].value} }

Import-Csv c:\1.csv | ForEach
{
  $_.name.ToLower() -match "^(?<last>[a-z -]+),( (?<middle>[a-z]+))? (?<first>[a-z-]+)( (?<code>[a-z0-9()]+))?$" | Out-Null
  $first   = $matches["first" ] -replace "[^a-z]","."
  $middle  = $matches["middle"] -replace "[^a-z]","."
  $middle2 = $matches["middle"] -replace "[^a-z]","."
  $last    = $matches["last"  ] -replace "[^a-z]","."
  $code    = $matches["code"  ] -replace "[()]"
  $company = $data[$_.company]
  If ($middle)  { $middle = "." + $middle }
  If ($code  )  { $code   = "." + $code }

  If ($_.UserId -like "z[18]*" -and $_.Company -like "TAL*") {
    $newSMTP  = "{0}.{1}.{2}@{3}" -f $first,$last,"sp",$company 
  }
  ElseIf ($_.Company -like "GAL*") {
    $newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"gal.com" 
  }
  ElseIf ($_.Company -like "TEST*") {
    $newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"test.com" 
  }
   ElseIf ($_.Company -like "DAL*") {
    $newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"dal.com" 
  }   
  Else {
    $newSMTP  = "{0}{1}{2}.{3}{4}@{5}" -f $first,$middle,$middle2,$last,$code,$company
  }   
  $mbox = Get-Mailbox $_.UserID
  $mbox
    
  If ($mbox.PrimarySMTPAddress -ne $newSMTP)
  {
    Write-Host  -ForegroundColor Green "Setting primary SMTP $newsmtp address for $mbox"
    $newsmtp | out-file -filepath c:\smtp4.csv -append
    set-mailbox -identity $_.UserID -PrimarySmtpAddress $newsmtp -EmailAddressPolicyEnabled $false -SingleItemRecoveryEnabled $true
    Set-Mailbox -Identity $User.userid -EmailAddresses $newsmtp2
    $newsmtp2 | out-file -filepath c:\smtp4.csv -append
  } else {
    Write-Host -ForegroundColor red -backgroundcolor yellow "$mbox has an SMTP-Address already exists in system"
  }
}

Open in new window

There was an error checking for test.com, and much superfluous code.

Well, the code looks like it does what you ask for. Which part does not work in particular?
0
Mandy_Author Commented:
Dear qlemo,

thanks for your help. I'm getting error below and can't find the problem

Cmdlet ForEach-Object at pipelineposition 2
enter the values for following Parameter:
Process[0]:
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
I managed to get that error myself a second ago in another script. The error is in line 6, please add a backtick ` to the end of line:
Import-Csv c:\1.csv | ForEach `

Open in new window

0
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

Mandy_Author Commented:
Thank you now i'm getting:

Die Argumenttransformation für den Parameter "PrimarySmtpAddress" kann nicht verarbeitet werden. NULL kann nicht in den
    + CategoryInfo          : InvalidData: (:) [Set-Mailbox], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-Mailbox
    + PSComputerName        : srv2008

Das Argument kann nicht an den Parameter "Identity" gebunden werden, da es NULL ist.
    + CategoryInfo          : InvalidData: (:) [Set-Mailbox], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Set-Mailbox
    + PSComputerName        : srv2008
                                                                {笀ോ传&"ows\ᄁಮက
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
That's an issue with the original logic. The initial script won't work either. Both scripts set either the primary or secondary email address vars, but not both. The conditions for both are contradictions, so this task seem to be impossible (and unreasonable). Unless I'm missing something ...
0
Mandy_Author Commented:
Hi,

i removed all other and put only the additionals creations of smtp addresses to a separate script Pls see
below. But still not working.Same error as above . any idea?   Thanks

Das Argument kann nicht an den Parameter "Identity" gebunden werden, da es NULL ist.
    + CategoryInfo          : InvalidData: (:) [Set-Mailbox], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Set-Mailbox
    + PSComputerName        : srv2008
                                           

$data = @{}
Select-String c:\hash2.txt -Pattern "([a-z]+).+?=.+?([a-z.]+)" |
  Select -Expand matches | ForEach { $data += @{ $_.groups[1].value = $_.groups[2].value} }

Import-Csv c:\1.csv | ForEach `
{
  $_.name.ToLower() -match "^(?<last>[a-z -]+),( (?<middle>[a-z]+))? (?<first>[a-z-]+)( (?<code>[a-z0-9()]+))?$" | Out-Null
  $first   = $matches["first" ] -replace "[^a-z]","."
  $middle  = $matches["middle"] -replace "[^a-z]","."
  $middle2 = $matches["middle"] -replace "[^a-z]","."
  $last    = $matches["last"  ] -replace "[^a-z]","."
  $code    = $matches["code"  ] -replace "[()]"
  $company = $data[$_.company]
  If ($middle)  { $middle = "." + $middle }
  If ($code  )  { $code   = "." + $code }


  If ($_.Company -like "GAL*") {
    $newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"gal.com" 
  }
  Elseif ($_.Company -like "VAL*") {
    $newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"test.com" 
    $newSMTP2 = "{0}{1}.{2}@{3}" -f $first,$middle,$last,"val.com" 
    
     }
  
  
    Write-Host  -ForegroundColor Green "Setting secondary SMTP $newsmtp2 address for $mbox"
    Set-Mailbox -Identity $User.userid -EmailAddresses $newsmtp2
    $newsmtp2 | out-file -filepath c:\smtp5.csv -append
  } 

Open in new window

0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Forgot to tell you about another error in the original script, and carried over. $User is not defined anywhere, though that should error out on $User,userid, not on Set-Mailbox ...
Line 29 should be:
   Set-Mailbox -Identity $_.Userid -EmailAddresses $newsmtp2

Open in new window

0

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
Mandy_Author Commented:
Gtreat Work
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.