I have created script for checking if VPN connection is disconnected and try to reconnect. Its also sending emails, when 1) cant ping VPN server with remote LAN address 2) VPN connection fails 3) VPN connection is established.
First email is sent and received properly, but Powershell gives error, when it have to send another email.
Code inside vpn.ps1 file:
$ip = "*.*.*.*"
$result = Get-WmiObject -Query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip'"
if($result.StatusCode -eq 0) {
} else {
Start-Sleep -s 15
$EmailFrom = "*@*.*"
$EmailTo = "*@*.*"
$Subject = "###"
$Body = "#####################################################"
$SMTPServer = "*.*.*.*"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, ***)
#$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("*@*.*", "*************");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
rasdial.exe ********** /DISCONNECT
rasdial.exe ******** ****** ******
Start-Sleep -Seconds 15
$ip = "*.*.*.*"
$result = Get-WmiObject -Query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip'"
if ($result.StatusCode -eq 0) {
$EmailFrom = "*@*.*"
$EmailTo = "*@*.*"
$Subject = "########"
$Body = "####################################"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
} else {
Start-Sleep -s 15
$EmailFrom = "*@*.*"
$EmailTo = "*@*.*"
$Subject = "################"
$Body = "##########################################"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
}
Log when running:
PS Microsoft.PowerShell.Core\FileSystem::***********> *******\vpn.ps1
#FIRST EMAIL SENT
No connections
Command completed successfully.
Connecting to *********...
Verifying username and password...
Registering your computer on the network...
Successfully connected to ******.
Command completed successfully.
Exception calling "Send" with "4" argument(s): "Failure sending mail."
At \\tsclient\C\New folder\vpn.ps1:26 char:9
+ $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
PS Microsoft.PowerShell.Core\FileSystem::******
I have sensored usernames, passwords, addresses etc. What is wrong with my script?
$SmtpServer- Mathias R. Jessen