2017-07-26 90 views
0

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

} 

回答

3

常見的錯誤,我也傾向於做什麼,你做的是這樣的:

if ($WhichNotification = "dosomething") 

但這是設置變量$WhichNotification爲「DoSomething的」是什麼 - 這是計算結果爲$true在一個if塊。

你想要做的是這樣的:

if ($WhichNotification -eq "dosomething")