简体   繁体   中英

Powershell not sending email sometime

I have some PS Scripts which is executed as follows:

Script1: Executed only once and it stores the entered password as a secure string in a text file

Script2: Executed repeatedly as a scheduled task. This invokes another script - Script3.

Script3: Every time, this script works fine for it's main task. But it has a mail sending feature which everytime gets failed. The script is as shown below:

$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
}

The errors which I recieve is:

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.

While executing the same mail function script alone, it works fine. But executing along with other script block is not working.

The code below works for me for the credentials

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM