我创建了用于检查VPN连接是否已断开并尝试重新连接的脚本。它还发送电子邮件,何时 1)不能使用远程LAN地址ping VPN服务器 2)VPN连接失败 3)建立VPN连接。
首先发送和接收电子邮件,但是当必须发送另一封电子邮件时,Powershell会给出错误。
vpn.ps1
文件中的代码:
$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)
}
}
运行时记录:
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::******
我已经感知了用户名,密码,地址等。我的脚本出了什么问题?
答案 0 :(得分:0)
您的$SMTPClient
对象未在else块中声明。
您需要在块中使用该对象的实例,在该块中使用它,或在外部声明它,以获得一个全局$SMTPClient
对象,该对象存在于块中。您还必须填写$SMTPClient.Credentials
。
最佳解决方案是,在第3行的if语句之前声明两者。
更新
移动这些行
$SMTPServer = "*.*.*.*"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, ***)
#$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("*@*.*", "*************");
中的那些if .. else ..
将它移到第2行,就在if块之前。