允许param接受Null或Empty String PowerShell

时间:2017-01-12 19:25:23

标签: email powershell bcc

在这个方法中,我添加了一个参数$ blindcopy,我希望能够在调用时使用bcc用户。在没有添加该参数的情况下测试此脚本后,一切都很好。添加此添加后,我收到一条错误,说“无法验证参数'bcc上的参数'。参数为null或为空”我尝试将AllowEmptyString()属性添加到参数但仍然没有运气。非常感谢任何帮助!

cls

$BccNull = ""

function SendEmail([string]$BodyString,[string]$SubjectString,[string[]]$EmailRecipientsArray,[string]$FileAttachment=$null,[AllowEmptyString()][string]$BlindCopy)
{ 
    $MethodName = "Send Email"

    # Send the HTML Based Email using the information from the tables I have gathered information in
    try
    {       
        $user = "user@foo.com"
        $pass = ConvertTo-SecureString -String "bar" -AsPlainText -Force
        $cred = New-Object System.Management.Automation.PSCredential $user, $pass

        $SMTPServer = "some.mail.server"
        if([string]::IsNullOrEmpty($BodyString))
        {
            $BodyString = " Body text was empty for user:  $ErrorMessageUserName"
        }


        if([string]::IsNullOrEmpty($FileAttachment)) 
        {
            Send-MailMessage -From "foo@bar.org" -To "bar@foo.org" -Subject $SubjectString -Bcc $BlindCopy -Body $BodyString -BodyAsHtml -Priority High -dno onSuccess, onFailure -SmtpServer $SMTPServer -Credential $cred
        }
        else
        {
            Send-MailMessage -From "foo@bar.org" -To "bar@foo.org" -Subject $SubjectString -Body $BodyString -BodyAsHtml -Attachments $FileAttachment -Priority High -dno onSuccess, onFailure -SmtpServer $SMTPServer -Credential $cred
        }   
    }
    catch
    {
        Write-Host "An Exception has occurred:" -ForegroundColor Red
        Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
        Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red 

        #$ErrorMessage =  "Script Error: "+ $_.Exception.Message + "`n" + "Exception Type: $($_.Exception.GetType().FullName)"
        #$SubjectLine = "Script Error:  " + $MethodName + " " + $ErrorMessageUserName

        #SendEmail -BodyString $ErrorMessage -SubjectString $SubjectLine -EmailRecipientsArray $EmailErrorAddress -FileAttachment $null

        $SuccessfulRun = $false
        #ReturnStatusError -CurrentStatus "Error" -ErrorMessage $_.Exception.Message
    }
}

SendEmail -BodyString "Test" -SubjectString "Test" -EmailRecipientArray "foo@bar.org" -FileAttachment $null -BlindCopy $BccNull

1 个答案:

答案 0 :(得分:2)

即使函数的view()->share('variables', function(){ //you can share whatever you want here and it will be availble in all views. }); 参数接受空字符串,-BlindCopy的{​​{1}}参数仍然没有。

我说你最好的做法是构建参数的哈希表,如果它们不为空则添加可选参数,然后在cmdlet上添加splat哈希表

-Bcc

但即使使用splatting,我可能仍然不允许参数Send-MailMessage使用空字符串。如果该消息不应该是BCC,那么应该完全省略参数。附件也是如此。如果空字符串显示为BCC收件人(或附件),则函数抛出错误。恕我直言。 YMMV。