user3803125
user3803125

Reputation: 3

Powershell using parameters to call functions based on which parameter is called

I am just jumping into PowerShell and am trying to write a script that executes functions I have created based on which parameter is called.

Example: send-notification -WhichNotifcation dosomething

Example2: send-notification -WhichNotification dosomethingelse

What I have now only calls the first function, but never the second. What am I doing wrong?

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"

}

Upvotes: 0

Views: 846

Answers (1)

Zerqent
Zerqent

Reputation: 523

Common mistake which I also tend to do, what you are doing is this:

if ($WhichNotification = "dosomething") 

What this does is to set the variable $WhichNotification to "dosomething" - something that evaluates to $true in an if-block.

What you want to do is this:

if ($WhichNotification -eq "dosomething") 

Upvotes: 4

Related Questions