Using powershell function Send-MailMessage getting an error: Cannot find an overload for "PSCredential"

Using powershell function Send-MailMessage getting an error: Cannot find an overload for "PSCredential"

我想使用 Send-MailMessage 函数通过 powershell 发送电子邮件。

我的 smtp 服务器需要用户名和密码。

我将它作为参数传递,但是出现错误。

 $CredUser = "123UserPass"
 $CredPassword = "1234/5678/999"
 $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CredUser, $CredPassword
 Send-MailMessage -SmtpServer "smtp.amazonaws.com" -Port 587 -Credential $Credential -UseSsl -From 'DBATeam@email.com' -To 'me@email.com' -Subject 'TEST'

错误信息:

New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At line:3 char:16
+ ... redential = New-Object -TypeName System.Management.Automation.PSCrede ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Send-MailMessage : Cannot process argument transformation on parameter 'Credential'. userName
At line:4 char:90
+ ... tp.us-east-2.amazonaws.com" -Port 587 -Credential $Credential -UseSsl ...
+                                                       ~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Send-MailMessage], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.SendMailMessage

我尝试使用 ConvertTo-SecureString -String "mypassword" 但也遇到了转换错误。

尝试:

$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force

如果您使用的是 5.1 或更高版本,您还可以使用 ::new() 静态方法代替 New-Object(完全可选)。

$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )
Send-MailMessage -SmtpServer "smtp.amazonaws.com" -Port 587 -Credential $Credential -UseSsl -From 'DBATeam@email.com' -To 'me@email.com' -Subject 'TEST'

如果你想增加一些可读性,你可以合并 splatting:

$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )

$SMTPParams = @{
   SmtpServer = 'smtp.amazonaws.com'
   Port       = 587
   Credential = $Credential
   UseSsl     = $true
   From       = 'DBATeam@email.com'
   To         = 'me@email.com'
   Subject    = 'TEST'
}

Send-MailMessage @SMTPParams

注意:有些人可能不喜欢看到密码。您可以将密码安全地存储在一个文件中,然后将其调回使用。只要是同一用户在同一台​​机器上。

$SecurePassword = 读取主机-提示“输入密码”-AsSecureString $安全密码 | ConvertFrom-安全字符串 |输出文件 C:\temp\SecurePasswword.txt

$CredPassword = Get-Content C:\temp\SecurePasswword.txt | ConvertTo-SecureString 
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )

显然您需要更改文件的路径,以免公布它。用前两行建立密码文件。然后使用当前脚本中的第二个 2 为您的 SMTP 命令设置凭据...

记录在案 here