I am working on a script that will mainly be used as a scheduled task to enabled mailuser by calling the update-recipient command.
But before it calls that command it will get for various issues that can cause errors.
Missing PrimarySMTP
Display name having a space at front or back.
The external email address being blank.
I have IF statements setup to check for those and then call a function that will save into an array the issue for that user.
Here is the script
<#
.SYNOPSIS
Enable-MailUsers Synced Mail Users in the Exchange environment
THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
Version .9, 30 June 2014
.DESCRIPTION
This script mail-enables Synced Mail Users and creates a CSV report of mail users that were enabled.
The following is shown:
* Report Generation Time
.PARAMETER SendMail
Send Mail after completion. Set to $True to enable. If enabled, -MailFrom, -MailTo, -MailServer are mandatory
.PARAMETER MailFrom
Email address to send from. Passed directly to Send-MailMessage as -From
.PARAMETER MailTo
Email address to send to. Passed directly to Send-MailMessage as -To
.PARAMETER MailServer
SMTP Mail server to attempt to send through. Passed directly to Send-MailMessage as -SmtpServer
.PARAMETER ScheduleAs
Attempt to schedule the command just executed for 10PM nightly. Specify the username here, schtasks (under the hood) will ask for a password later.
.EXAMPLE
Generate the HTML report
.\Enable-MailUsers.ps1 -SendMail -MailFrom Chuck@Contoso.com -MailTo Admindl@contaso.com -MailServer ex1.contoso.com -ScheduleAs SvcAccount
#>
param(
[parameter(Position=0,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Send Mail ($True/$False)')][bool]$SendMail=$false,
[parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail From')][string]$MailFrom,
[parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail To')]$MailTo,
[parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail Server')][string]$MailServer,
[parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Schedule as user')][string]$ScheduleAs
)
# Sub Function to neatly update progress
function _UpProg1
{
param($PercentComplete,$Status,$Stage)
$TotalStages=5
Write-Progress -id 1 -activity "Mail enabled Objects" -status $Status -percentComplete (($PercentComplete/$TotalStages)+(1/$TotalStages*$Stage*100))
}
#Sub Function create ErrObject output
function _ErrObject{
Param($name,
$errStatus
)
If(!$err){
Write-Host "error detected"
$script:err = $True
}
$ErrObject = New-Object -TypeName PSObject
$Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
$Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
$script:ErrOutput += $ErrObject
}
# 1. Initial Startup
# 1.0 Check Powershell Version
if ((Get-Host).Version.Major -eq 1)
{
throw "Powershell Version 1 not supported";
}
# 1.1 Check Exchange Management Shell, attempt to load
if (!(Get-Command Get-ExchangeServer -ErrorAction SilentlyContinue))
{
if (Test-Path "D:\Exchsrvr\bin\RemoteExchange.ps1")
{
. 'D:\Exchsrvr\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
} elseif (Test-Path "D:\Exchsrvr\bin\Exchange.ps1") {
Add-PSSnapIn Microsoft.Exchange.Management.PowerShell.Admin
.'D:\Exchsrvr\bin\Exchange.ps1'
} else {
throw "Exchange Management Shell cannot be loaded"
}
}
# 1.2 Check if -SendMail parameter set and if so check -MailFrom, -MailTo and -MailServer are set
if ($SendMail)
{
if (!$MailFrom -or !$MailTo -or !$MailServer)
{
throw "If -SendMail specified, you must also specify -MailFrom, -MailTo and -MailServer"
}
}
# 1.3 Check Exchange Management Shell Version
if ((Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue))
{
$E2010 = $false;
if (Get-ExchangeServer | Where {$_.AdminDisplayVersion.Major -gt 14})
{
Write-Warning "Exchange 2010 or higher detected. You'll get better results if you run this script from an Exchange 2010/2013 management shell"
}
}else{
$E2010 = $true
$localserver = get-exchangeserver $Env:computername
$localversion = $localserver.admindisplayversion.major
if ($localversion -eq 15) { $E2013 = $true }
}
#Get date
$filedate = get-date -uformat "%m-%d-%Y"
$filedate = $filedate.ToString().Replace("0", "")
#Get the valid users that are not mail-enabled
_UpProg1 1 "Getting User List" 1
#$Users = Get-mailuser -ResultSize unlimited -OrganizationalUnit "R0018.COLLABORATION.ECS.HP.COM/Accounts/AbbVienet/Users" | ?{$_.legacyexchangeDN -eq ""}
$i = 0
$output = @()
$errOutput = @()
$err = $False
#2 Process users
ForEach ($User in $Users){
$i++
_UpProg1 ($i/$Users.Count*100) "Updating Recipients" 2
If ($user.ExternalEmailAddress -eq $null){
_ErrObject $user.Name, "Missing External Email Address"
}
ElseIf($user.DisplayName -NotLike "* "){
_ErrObject $user.Name, "DisplayName contains a trailing space"
}
ElseIf($user.DisplayName -NotLike "_*"){
_ErrObject $user.Name, "DisplayName contains a Leading space"
}
ElseIf($user.PrimarySmtpAddress -eq $null){
_ErrObject $user.Name, "Missing Primary SMTP address"
}
Else{
#Disable EmailAddressPolicy on these users
Set-Mailuser $User.Name -EmailAddressPolicyEnabled $false
#pass to Update-recipient
Update-Recipient $User.Name
$LEDN = Get-MailUser $User.Name | Select {$_.LegacyExchangeDN}
If ($LEDN -ne ""){
$object = New-Object -TypeName PSObject
$X500 = "x500:" + $LEDN.'$_.LegacyExchangeDN'
$object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $User.Name
$object | Add-Member -Name 'x500' -MemberType Noteproperty -Value $X500
$output += $object
}
}
}
#Creating CSVFile Output
_UpProg1 99 "Outputting CSV file 3" 3
$CSVFile = "c:\scripts\Mail-enable\Mailenabled_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
If($err){
$ErrCSVFile = "c:\scripts\Mail-enable\ProblemUsers_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
$errOutput | Select-Object Name, Comment | ConvertTo-CSV -NoTypeInformation > $ErrCSVFIle
}
$Output | ConvertTo-Csv -NoTypeInformation > $CSVFile
if ($SendMail)
{
_UpProg1 95 "Sending mail message.." 4
If($err){
Send-MailMessage -Attachments $CSVFile,$ErrCSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
}
Else{
Send-MailMessage -Attachments $CSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
}
}
if ($ScheduleAs)
{
_UpProg1 99 "Attempting to Schedule Task.." 4
$dir=(split-path -parent $myinvocation.mycommand.definition)
$params=""
if ($SendMail)
{
$params+=' -SendMail:$true'
$params+=" -MailFrom:$MailFrom -MailTo:$MailTo -MailServer:$MailServer"
}
$task = "powershell -c \""pushd $dir; $($myinvocation.mycommand.definition) $params\"""
Write-Output "Attempting to schedule task as $($ScheduleAs)..."
Write-Output "Task to schedule: $($task)"
schtasks /Create /RU $ScheduleAs /RP /SC DAILY /ST 22:00 /TN "Enable Mail Users" /TR $task
}
The Problem is that when I look at the $errOutput I see things but when I pipe the $erroutput to convertTo-CSV I get this within the CSV file. I think its because I an calling a function to do the updating. But not sure.
Jeff C