Loops powershell中的结束循环
嘿,伙计们 我希望在脚本中有一个循环,但当我使用else时,它需要停止Loops powershell中的结束循环,loops,powershell,if-statement,Loops,Powershell,If Statement,嘿,伙计们 我希望在脚本中有一个循环,但当我使用else时,它需要停止 do { ##script## if ((Get-Service $service ).Status -eq "stopped") { Write-Host 'Send email message, a service has been stopped' Send-MailMessage -From $From -to $To -Subject $Subject ` -Body $Body -SmtpServer
do {
##script##
if ((Get-Service $service ).Status -eq "stopped") {
Write-Host 'Send email message, a service has been stopped'
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $mycredentials -Attachments $service_text -ErrorAction SilentlyContinue
$stopen = "stoppen"
}
else { write-host "re execute script" } while ((Get-Service $service ).Status -eq "stopped")
}
如何在else语句中结束循环
谢谢
看完整的脚本,错误在脚本的末尾。
如果服务正在运行,脚本需要再次检查它。如果服务停止,我需要收到一封电子邮件。不,我不想收到2亿封电子邮件,只要一封:P
## PSVersion: Required Powershell V 3.0
## Author: Gijs Liefers
## Script: If a service has been stopped you will receive an email
## Requirements: Internet connection, Port 587 open for mailing and run this script as administrator.
## Version 1.0
## - Initial Release
## Date: 14-1-2015
### Note:
## - Set-Exexution Policy ## --
## if you want to run this script you have to set the ExecutionPolicy to RemoteSigned.
## To do this open Powershell run as Administrator and type Set-ExecutionPolicy remotesigned.
## Click on yes to all
### -- LOOP
$doetiehettest = Test-Path C:\Windows
### --- Make Directory --- ####
########################################################################
# PowerShell checks, then creates a file and folder
Clear-Host
$Location = "$env:userprofile\documents\PS-Script-Services"
$LocationFile = "$env:userprofile\documents\"
If((Test-Path $Location) -eq $False) {
New-Item -Path $Locationfile -name "PS-Script-Services" -ItemType "directory" | out-null
} # End of folder exists test
#region Main Variables
########################################################################
## -- Locations -- ##
########################################################################
$documents = "$env:userprofile\documents\PS-Script-Services\"
$password_location = "$env:userprofile\documents\PS-Script-Services\Password.txt"
$username_location = "$env:userprofile\documents\PS-Script-Services\Username.txt"
$source_adres = "$env:userprofile\documents\PS-Script-Services\Source.txt"
$destination_adres = "$env:userprofile\documents\PS-Script-Services\Destination.txt"
$SMTP_adres = "$env:userprofile\documents\PS-Script-Services\SMTP.txt"
$Service_text = "$env:userprofile\documents\PS-Script-Services\Services.txt"
$Data_service = "$env:userprofile\documents\PS-Script-Services\Output-Services.txt"
########################################################################
##############################################
### -- Email information -- ###
##########################################
Write-host " "
Write-Host "Welcome to a automated script! You will receive a email if a specific service has been stopped" -BackgroundColor Black -ForegroundColor green
Write-host "All the files of this script are located on $documents" -BackgroundColor Black -ForegroundColor Yellow
Write-host "If you have any questions about this script send a mail to GijsLiefers@outlook.com" -BackgroundColor Black -ForegroundColor green
############################################
## Test-Path ##
$source_test = Test-Path $source_adres
$des_test = Test-Path $destination_adres
$smtp_test = Test-Path $SMTP_adres
$service_test = Test-Path $Service_text
$data_test = Test-Path $Data_service
################################
#endregion
#-loop-# -- Email settings -- ##
If (($source_test -eq $false) -and ($des_test -eq $false) -and ($smtp_test -eq $false)) {
Read-Host "What is the source mailadres? (inclucing @example.com)" | Out-file $source_adres
Read-Host "What is the destination mailadres? (inclucing @example.com)" | Out-file $destination_adres
Write-Host "This script using SSL on port 587 for the SMTP server " -BackgroundColor Black -ForegroundColor Yellow
Read-Host "What is the smtp server? (Example: smtp.gmail.com" | Out-file $SMTP_adres
}
Else {
Write-host " "
write-host "Are the email settings right? SMTP: $get_smtp, From (source): $get_source, To (destination): $get_dest" -BackgroundColor white -ForegroundColor Black
write-host "Otherwise edit the settingsfolder PS-Script-Services on the following path $documents" -BackgroundColor Black -ForegroundColor Red
}
########### -- STORED CREDENTIAL CODE ###################################
## Test-Path ##
$FileExists = Test-Path $password_location, $username_location
#-loop-# -- Email Credentials -- ##
if ($FileExists -eq $false) {
Write-Host 'Credential file not found. Enter your username and password:' -ForegroundColor Red
Read-Host "Enter Username from your email account most of the time don't add @example.com" | Out-File $username_location
Read-Host "Enter Password from your email account" -AsSecureString | ConvertFrom-SecureString | Out-File $password_location
$Username = get-content $username_location
$Password = get-content $password_location | convertto-securestring
$mycredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username,$Password
}
else {
Write-Host "Using your stored credential file on path $password_location and $username_location " -ForegroundColor Green
$Username = get-content $username_location
$Password = get-content $password_location | convertto-securestring
$mycredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username,$Password
}
### -- Get-Content -- ##
#############################################################################################
$get_smtp = Get-Content $SMTP_adres -ErrorAction SilentlyContinue
$get_source = Get-Content $source_adres -ErrorAction SilentlyContinue
$get_dest = Get-Content $destination_adres -ErrorAction SilentlyContinue
$service = Get-Content $Data_service -ErrorAction SilentlyContinue
##################################################################################################
#-loop-# -- Get-Service -- ##
if ($Data_test -eq $false) {
Write-Host "To view your Services go to Start --> en typ services, or go to Powershell and type get-service" -BackgroundColor Black -ForegroundColor Yellow
write-host "Which Services do you want to monitor? (Example: `n Teamviewer `n BITS `n DHCP (Use a LIST !!!!)"
write-host "This script only works when a service has been stopped" -BackgroundColor Black -ForegroundColor Yellow
New-Item $Data_service -Type file -Value "Add the services in a row and delete this rule!" -ErrorAction SilentlyContinue| Out-Null
sleep 3
Invoke-Item $Data_service
sleep 25
}
else { write-host "The following services are selected: $service . Edit them if necessary. For editing Delete the folder $location" -BackgroundColor white -ForegroundColor Black
}
## - Just a test ## --
do {
## -- Attachment content # --
$service_input = Get-Content $Service_text -ErrorAction SilentlyContinue
##############################################################################
##-- Attachment --##
Get-Service $service | Out-File $Service_text
## -- Send Mail message -- ##
##############################################################################
$title = "Incident! Service has been stopped on $env:COMPUTERNAME "
$message = "Dear Sir/Madam,
There is a issue on the following server $env:Computername. One or multiple service(s) has been stopped.
Look at the attachment which service has been stopped
$service
We hope that we give you enough information to solve this problem
Kind Regards,
Powershell Automated Script
Tech support
"
##############################################################################
#Establishes connection to MailServer with the specified user acccount and password.
## -- Note .. #--
## If you add the information for the first time there will be a error message ## .. Run the script again
$From = $get_source
$To = $get_dest
$Cc = "YourBoss@YourDomain.com"
$Subject = $title
$Body = $message
$SMTPServer = $get_smtp
$SMTPPort = "587"
if ((Get-Service $service ).Status -eq "stopped") {
Write-Host 'Send email message, a service has been stopped'
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $mycredentials -Attachments $service_text -ErrorAction SilentlyContinue
}
else {
write-host "re execute script"
;break
}
} while((Get-Service $service ).Status -eq "stopped")
使用
break
关键字中断循环:
$i = 0
do{
if($i -lt 5)
{
$i++
}
else
{
break
}
} while ($true)
或者正确使用while()
子句:
$i = 0
do{
$i++
} while ($i -lt 5)
`}else{write host“re execute script”break}}位于C:\Users\gijs\OneDrive\!Mijn Documenten\10-Scripts\Send email if service stopped\Send email if service stopped.ps1:195 char:2+}+~ do循环中while或until关键字缺失。+CategoryInfo:ParserError:(:)[],ParentContainesErrorRecordException+FullyQualifiedErrorId:Missing while或Untillindowwhile`对不起,我的答案有误,现在更新了。您还需要一个
在break
之前在else
blockelse{write host“re-execute script”;break}准确,然后while((Get Service$Service).Status-eq“stopped”)
在do{}
块之外它不工作:(如果服务正在运行,脚本必须再次运行。如果服务已停止,我需要接收电子邮件。如果服务已停止,您是否应该尝试启动该服务?或者您是否只想继续发送垃圾邮件,直到有人联机并手动启动该服务?因此,如果服务正在运行,您希望保留do{}(
循环永远运行,检查状态?如果服务在某一点停止怎么办?循环是否仍应继续?限制电子邮件?引入延迟?