【问题标题】:Powershell using parameters to call functions based on which parameter is calledPowershell使用参数调用函数根据调用哪个参数
【发布时间】:2023-05-19 07:21:01
【问题描述】:

我只是跳入 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"

}

【问题讨论】:

    标签: function powershell parameter-passing


    【解决方案1】:

    我也倾向于做的常见错误,你正在做的是:

    if ($WhichNotification = "dosomething") 
    

    这样做是将变量 $WhichNotification 设置为“dosomething” - 在 if 块中计算为 $true

    你想做的是这样的:

    if ($WhichNotification -eq "dosomething") 
    

    【讨论】: