我有一些PS脚本执行如下:
Script1:仅执行一次并将输入的密码作为安全字符串存储在文本文件中
脚本2:作为计划任务重复执行。这会调用另一个脚本 - Script3。
Script3:每次,这个脚本都可以正常运行它的主要任务。但它有一个邮件发送功能,每次都失败。脚本如下所示:
$time = (Get-Date).ToShortTimeString()
$destzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time")
$desttime = [System.TimeZoneInfo]::ConvertTimeFromUtc((Get-Date).ToUniversalTime(), $destzone)
$desttime = $desttime.ToShortTimeString()
if($time -eq $desttime)
{
#do nothing
}
else
{
***Main Function of script***
#E-mail Function
#Getting Credential from txt file
$passw = Get-Content C:\timezone\mailcred.txt | convertto-securestring
$crede = new-object -typename System.Management.Automation.PSCredential -argumentlist "user@domain.in",($passw)
#Mail Function
$param = @{
SmtpServer = 'smtp.gmail.com'
Port = 587
UseSsl = $true
Credential = $crede
From = 'user@domain.in'
To = 'user@domain.in'
Subject = 'Alert - Timezone changed'
Body = "Time zone changed to Central Standard Time for system with IP $ip"
}
Send-MailMessage @param
}
我收到的错误是:
Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "password" is null. Change the value of argument "password" to a non-null value."
Cannot validate argument on parameter 'Credential'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
单独执行相同的邮件功能脚本时,它可以正常工作。但是与其他脚本块一起执行是行不通的。
答案 0 :(得分:0)
以下代码适用于我的凭据
# Create PSCredential
$secstr = New-Object -TypeName System.Security.SecureString
$secstr = ConvertTo-SecureString -String $password -AsPlainText -Force
$credentials = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList "user", $secstr