【问题标题】:Student, automating email to an admin on creation of a new user powershell学生,在创建新用户 powershell 时自动向管理员发送电子邮件
【发布时间】:2020-05-29 02:28:17
【问题描述】:

尝试在创建新用户时向管理员发送电子邮件。 这似乎第一次运行,但第二次运行失败。 我认为这是我第二次创建新对象的问题,但我不熟悉 PScredential,以及如何第二次调用它而不是再次创建它,我假设这将是某种形式的 if 语句,但我不知道在 if 中调用什么。

这是我的代码

$password = ConvertTo-SecureString “Password” -AsPlainText -Force

$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',"$password")

Send-MailMessage -SmtpServer 'smtp.mailtrap.io' -Credential $cred -UseSsl -From 'server@gmail.com' -To 'admin@gmail.com' -Subject 'TEST'


这是错误信息

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

【问题讨论】:

标签: powershell email automation


【解决方案1】:

让我们看看文档 https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.pscredential?view=pscore-6.2.0

我们可以看到有2个构造函数

PSCredential(PSObject)

PSCredential(String, SecureString)

看起来在帖子示例中 PSCredential(String, SecureString) 正在尝试使用。

在示例中

$password = ConvertTo-SecureString “Password” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',"$password")

因为"$Password" 被放在引号中,所以它把SecureString 变成了一个普通的String

修复方法是删除 qoutes "

这是一份工作副本

$password = ConvertTo-SecureString “Password” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',$password)
Send-MailMessage -SmtpServer 'smtp.mailtrap.io' -Credential $cred -UseSsl -From 'server@gmail.com' -To 'admin@gmail.com' -Subject 'TEST'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2010-11-27
    • 1970-01-01
    • 2013-10-28
    相关资源
    最近更新 更多