[英]If error, skip to next in Powershell (Microsoft Teams)
Good evening,晚上好,
I have written a piece of code in Powershell that takes a .csv file as input, and create a new Microsoft Team with the channels and users in the .csv我在 Powershell 中编写了一段代码,将 .csv 文件作为输入,并使用 .csv 中的渠道和用户创建一个新的 Microsoft 团队
The script is working, but i dont really like the part where i add the owners to the team.该脚本正在运行,但我真的不喜欢将所有者添加到团队的部分。 I recieve a list of ID's in the .csv file, but i can only add the owners with a mailadres.
我在 .csv 文件中收到一个 ID 列表,但我只能添加带有 mailadres 的所有者。 This would be a easy loop, but there are 3 possible domains that the user is connected to.
这将是一个简单的循环,但用户连接到 3 个可能的域。
My goal is to have a piece of code that adds @domain1.nl to the ID that i get in the .csv, and try to add the user.我的目标是有一段代码将@domain1.nl 添加到我在 .csv 中获得的 ID,并尝试添加用户。 if i receive a error because that address does not exist, it will try to add the owner with @domain2.nl and @domain3.nl added to it.
如果我因为该地址不存在而收到错误,它会尝试添加@domain2.nl 和@domain3.nl 的所有者。 If nothing works, it should give a Write-Host that says "This domain has to be added"
如果没有任何效果,它应该给出一个写主机,上面写着“必须添加这个域”
Below is the piece of code that works, but i think its not the best way to it and it could be improved.下面是一段有效的代码,但我认为这不是最好的方法,可以改进。
#Adding the owners to the Team
if ($d.ID) {
$Error.Clear()
try {
$ID = $d.ID + "@domain1.nl"
Add-TeamUser -GroupId $GroupID -User $ID -Role Owner
} catch { "Error occured" }
if ($Error) {
$Error.Clear()
try {
$ID = $d.ID + "@domain2.nl"
Add-TeamUser -GroupId $GroupID -User $ID -Role Owner
} catch { "Error occured" }
if ($Error) {
$Error.Clear()
try {
$ID = $d.ID + "@domain3.nl"
Add-TeamUser -GroupId $GroupID -User $ID -Role Owner
} catch { "Error occured" }
if ($Error) {
Write-Host "This domain has to be added to the code"
}
}
}
}
Many thanks in advance!提前谢谢了!
Use try
/ catch
inside a foreach
loop:在
foreach
循环中使用try
/ catch
:
$ok = $false
foreach ($domain in '@domain1.nl', '@domain2.nl', '@domain3.nl') {
try {
Add-TeamUser -GroupId $GroupID -User ($d.ID + $domain) -Role Owner
$ok = $true
} catch {
Write-Warning "Error occurred with domain $domain."
}
if ($ok) { break }
}
if (-not $ok) {
Write-Error 'This domain has to be added to the code'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.