• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 270
  • Last Modified:

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

0
Mandy_
Asked:
Mandy_
  • 4
  • 4
1 Solution
 
QlemoC++ DeveloperCommented:
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
 
QlemoC++ DeveloperCommented:
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
A Cyber Security RX to Protect Your Organization

Join us on December 13th for a webinar to learn how medical providers can defend against malware with a cyber security "Rx" that supports a healthy technology adoption plan for every healthcare organization.

 
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
 
QlemoC++ DeveloperCommented:
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
 
QlemoC++ DeveloperCommented:
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
 
Mandy_Author Commented:
Gtreat Work
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now