使用参数调用基于哪个参数调用函数的Powershell
问题描述:
我刚刚跳入PowerShell,并试图编写一个脚本,该脚本执行基于调用哪个参数而创建的函数。使用参数调用基于哪个参数调用函数的Powershell
例:发送通知-WhichNotifcation DoSomething的
例2:发送通知-WhichNotification dosomethingelse
我现在只调用第一个函数,但从来没有第二个。我究竟做错了什么?
param(
[parameter(Mandatory = $true)]
[ValidateSet("dosomething", "dosomethingelse")]
[ValidateNotNull()]
[string]$WhichNotification
)
#Variables
$mailTo = "[email protected]"
$mailFrom = "[email protected]"
$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"
}
答
常见的错误,我也倾向于做什么,你做的是这样的:
if ($WhichNotification = "dosomething")
但这是设置变量$WhichNotification
为“DoSomething的”是什么 - 这是计算结果为$true
在一个if块。
你想要做的是这样的:
if ($WhichNotification -eq "dosomething")