gpt4 book ai didi

powershell - Powershell Function为数组中的每个项目运行(我不希望这种情况发生)

转载 作者:行者123 更新时间:2023-12-03 00:03:07 25 4
gpt4 key购买 nike

我创建了一个脚本来配置Lync用户,需要通过电子邮件发送有关新配置的重要详细信息(例如分配的LineURI)。同样,任何错误都需要发送(当然会出现一些友好的错误消息:)。

因此,我创建了一些包含所有相关数据的CSV文件。

然后我创建了一个函数:

Function Send-Email ($attachArray) {
# Get a list of to addresses
$toAddresses = "foo@corp.local","bar@corp.local"

# Process replacments
Replace-EmailMasks

# Send conditionaly
Switch ($attachArray) {
$null {
Send-MailMessage -SmtpServer "internalrelay.corp.local" `
-From "test@andylab.local" -To $toAddresses `
-Subject "There should really be something more informative here" `
-BodyAsHTML $SCRIPT:htmlBody
}

Default {
Send-MailMessage -SmtpServer "internalrelay.corp.local" `
-From "test@andylab.local" -To $toAddresses `
-Subject "There should really be something more informative here" `
-BodyAsHTML $SCRIPT:htmlBody
-Attachments $attachArray
}
}
}

这是我如何调用它:
# Logic, then send
If (($npSuccess -gt 0) -AND ($errorsExist -gt 0)) {
# Attaching both
# Heres the summary paragraph
$SCRIPT:customSummary = '<p>Success and errors :|</p>'
# Now I'm sending it.
Send-Email "$($tempPlace.fullname)\NewProviSsion_Output.csv","$($tempPlace.fullname)\Errors_Output.csv"
} ElseIf ($npSuccess -gt 0) {..} # output-generating Success
ElseIf ($errorsExist -gt 0) {..} # Failed somewhere
Else {..} # no output-generating Success, no overall fails

现在可以了;电子邮件看起来不错,可以发送给谁,还可以附加文件等。

问题是:
对于我在$ attachArray中指定的许多文件,这就是发送多少电子邮件。电子邮件完全相同,多次发送给同一个人。

好像我正在这样做:
ForEach ($item in $attachArray) {
Send-Email "$($tempPlace.fullname)\NewProviSsion_Output.csv","$($tempPlace.fullname)\Errors_Output.csv"
}

除了我不是。

为了阐明我的目标,我希望仅在一次将电子邮件发送到$ toAddresses中的所有人。

谁能启发我有关这里发生的事情?
也许我星期一早上过得很糟糕。

最佳答案

switch语句为数组的每个元素触发。此行为是documented(检查Get-Help about_Switch):

If the test value is a collection, such as an array, each item in the collection is evaluated in the order in which it appears.



请改用常规条件语句(因为无论如何您只有2种情况):
if ($attachArray -eq $null) {
Send-MailMessage -SmtpServer "internalrelay.corp.local" `
-From "test@andylab.local" -To $toAddresses `
-Subject "There should really be something more informative here" `
-BodyAsHTML $SCRIPT:htmlBody
} else {
Send-MailMessage -SmtpServer "internalrelay.corp.local" `
-From "test@andylab.local" -To $toAddresses `
-Subject "There should really be something more informative here" `
-BodyAsHTML $SCRIPT:htmlBody
-Attachments $attachArray
}

关于powershell - Powershell Function为数组中的每个项目运行(我不希望这种情况发生),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17148200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com