在下面的脚本中,我让它运行良好,但是一旦发生错误,它就无法在错误之前停止的地方继续,我对我在这方面缺少什么感到有点困惑,所以任何帮助都会很棒。
首先,它加载一个包含通讯组列表的文本文件,然后使用 Exchange 查询此列表以获取完全匹配的显示名称,然后循环通过 CSV 将每个用户添加到通讯组列表,这一切都很好,它是什么时候发生错误就是问题所在。
catch 语句理解错误然后执行任务,一旦任务完成,它会在 catch 语句中而不是在 try 中从 forloop 运行脚本。
我添加了函数 UpdateDistros
允许脚本再次运行,但问题是它再次遍历整个文本文件,而不是从发生错误的位置开始,即使它在第 1 行或第 25 行。
下面是代码;
## ##
## Adds users from text file to distributon lists ##
## ##
######################################################
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName 'UserPrincipalName'
Function UpdateDistros{
$ErroractionPreference = 'Stop'
$Path = "C:\INSTALLS\Exchange-Distro_Lists\Data"
$res = $Path+"\Results"
$txt1 = "Distros.txt"
$txt2 = "Results.txt"
$txt3 = "Mail_Contacts.txt"
$txt4 = "Errors.txt"
$DS1 = gc $Path"\"$txt1 # Gets information from a text file
$1 = "Error Occurred"
$R1 = $res+"\"+$txt2
$R2 = $res+"\"+$txt3
$R3 = $res+"\"+$txt4
try{
Foreach($DS in $DS1){ # Cycles through text file
$DSG = Get-DistributionGroup -identity $DS | Select * -ExpandProperty Alias # Gets display name for distribution group
$DS2 = $path+ "\"+ "$DSG.csv"
$NUS = Import-csv $DS2
#Foreach { $_ + '@zenith.co.uk' } | ` # ammends all users in each text file to contain @zenith.co.uk
#Foreach { $_ –replace “ “,”.” } # ammends all users in each text file to contain @zenith.co.uk
Foreach($NU in $NUS){ # Cycles through each record in each text file
$N1 = $NU.DP
$N2 = $NU.EM
#$NU
Add-DistributionGroupMember -identity $DS -Member $N1 #Adds each record to the correct distribution List
"$N1 added to $DS" | Out-file $R1 -Append
Write-host "Completed Script"
}
}
}
Catch{
$Erw = $_.Exception.Message
$Erw = $Erw -replace """",""
$NMC = get-content $DS2
$Rers = "Couldn't find object $N1. Please make sure that it was spelled correctly or specify a different object."
$Erw
$Rers
$A1 = $N1 -replace "\s",""
if($Erw -contains $Rers){
Foreach($NM in $NMC){
Write-host $1
Write-host $Erw
$Unq = 'There are multiple recipients matching identity "$N1". Please specify a unique value.'
$ERM = $_.Exception.Message
if($ERM -contains $Unq){
$NU = $NU + '- Cartwright'
New-MailContact -Name $N1 -ExternalEmailAddress $N2 -Alias $A1
"New Mail contact created for $N1" | Out-file $R2 -Append -ErrorAction continue
UpdateDistros
}
ElseIf($Erw -contains $Rers){
New-MailContact -Name $N1 -ExternalEmailAddress $N2 -Alias $A1
"New Mail contact created for $N1" | Out-file $R2 -Append -ErrorAction continue
UpdateDistros
}
Else{
$Erw | Out-file $R3 -Append -ErrorAction continue
UpdateDistros
}
}
}
Else{
$Erw | Out-file $R3 -Append -ErrorAction continue }
UpdateDistros
}
}
UpdateDistros