我刚刚进入PowerShell并尝试编写一个脚本,该脚本根据调用的参数执行我创建的函数。
示例:send-notification -WhichNotifcation dosomething
示例2:发送通知-WhichNotification dosomethingelse
我现在只调用第一个函数,但从不调用第二个函数。我做错了什么?
param(
[parameter(Mandatory = $true)]
[ValidateSet("dosomething", "dosomethingelse")]
[ValidateNotNull()]
[string]$WhichNotification
)
#Variables
$mailTo = "user@something.com"
$mailFrom = "user@somethingelse.com"
$smtpServer = "x.x.x.x"
$mailSubject1 = "Do Something"
$MailSubject2 = "do something else"
function Send-dosomething
{
Send-MailMessage -To $mailTo -From $mailFrom -SmtpServer $smtpServer -Subject $mailSubject1 -Body "message1"
}
function Send-dosomethingelse
{
Send-MailMessage -To $mailTo -From $mailFrom -SmtpServer $smtpServer -Subject $MailSubject2 -Body "message2"
}
if ($WhichNotification = "dosomething") {
Send-dosomething
}
elseif ($WhichNotification = "dosomethingelse") {
Send-dosomethingelse
}
else {
Write-Host "Invalid"
}
答案 0 :(得分:3)
我也倾向于做的常见错误,你正在做的是:
if ($WhichNotification = "dosomething")
这样做是为了将变量$WhichNotification
设置为“dosomething” - 在if-block中评估为$true
的东西。
你想要做的是:
if ($WhichNotification -eq "dosomething")