我是Powershell的新手,在学习阶段,我尝试创建一个脚本来自动完成任务。此脚本无法正常工作。你能否回顾一下,给我一些帮助。
我的任务是,
我试图找出处于停止状态并尝试启动它的SQL服务(多个服务器中的多个SQL服务),等待一分钟完成服务启动并再次验证服务状态。如果它仍处于停止状态,我正在尝试发送电子邮件给人们设置操作。
请您查看以下代码并更正错误,我试图找到但无法做到
#Define servers & Services Variables
$Servers = GC "E:\Bhanu\SQLServer.txt"
$Services = GC "E:\Bhanu\SQLService.txt"
#Function Call
Function ServiceStatus ($Servers, $Services)
{
foreach ($Server in $Servers)
{
foreach ($Service in $Services)
{
$Servicestatus = get-service -ComputerName $Server -Name $Service
if ($Servicestatus.Status -eq "Stopped")
{
Start-service $Service
Start-Sleep -Seconds 60
$ServiceStatus1 = Get-Service -ComputerName $Server -Name $Service
if ($Servicestatus1.Status -eq "Stopped")
{
FuncMail -To “abc@gmail.com” -From “abc@gmail.com” -Subject $Server + $Service "fails to Start, Take immediate Action to avoid Impact” -Body $ServiceName "Service fails to Start, Take immediate Action to avoid Impact” -smtpServer “servername”
}
}
}
}
}
function FuncMail
{
#param($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
param($To, $From, $Subject, $Body, $smtpServer)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $From
$msg.To.Add($To)
$msg.Subject = $Subject
$msg.IsBodyHtml = 1
$msg.Body = $Body
$smtp.Send($msg)
}
servicestatus $ Servers $ Services
如果您需要我的任何内容,请告诉我
答案 0 :(得分:3)
嗨,这不是最好的方法,我正在快速地做到这一点。
注意%= foreach-object; ?=位置对象。
如果您的smtp服务器需要身份验证,则必须将密码保存在一个文件中,否则不要使用read-host -assecurestring | convertfrom-securestring | out-file "C:\Secure\Password.txt"
运行它
我还假设您将服务器保存在一个文件中
我的解决方案是启动所有sql server服务,如果你想要开始具体只需将服务名称保存在单独一行的一个文件上。
执行下面的代码。
#Loading Server and service details
$Services=Get-content C:\PS\Service.txt
$servidores=get-content C:\PS\Servers\Servers.txt
#Loading Mail credential
$Mailpasswordpath="C:\PS\Securestring.txt"
$Mailusername="DOmain\User"
$password=cat $Mailpasswordpath |ConvertTo-Securestring
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Mailusername,$password
$servidores|Foreach-Object{Get-Service -ComputerName $_ -Name $Services }| #Get the services running on all servers
Where-Object{$_.Status -eq "Stopped"}| #Which status is equal stopped
Foreach-Object{
$_.Start(); #try to start
Start-Sleep -Seconds 60; #wait one minute
$_.Refresh(); #refresh then service to update status
#validate is status still stopped
if($_.Status -eq "Stopped")
{
#LOADING Mail details
$To="user@domain.com"
$subject="$($_.MachineName) $($_.Name) fails to Start, Take immediate Action to avoid Impact"
$From="ServiceStatus@domain.com"
$smtp="Server.domain.com"
$body="$($_.Name) Service fails to Start, Take immediate Action to avoid Impact"
#Sending email to notify
Send-MailMessage -To $To -Subject $subject -From $From -SmtpServer $smtp -Body $body -Credential $Cred
}
}
P.S:这不是我决定解决这个问题的最佳方法。如果你愿意,我们可以一起创建一个函数,然后再测试它。