简体   繁体   中英

Powershell script if and

I want to make a script that checks two time if a process is running. First I would like to check normally if a process is running and second time I want to wait 30 seconds until the next check.

Here I have something like this:

$check=Get-Process hl -ErrorAction SilentlyContinue
if ($check -eq $null) {
Start-Sleep -s 30
}

If in both cases the process is not running I want poweshell to send me a mail with this :

$EmailFrom = “mail@gmail.com”
$EmailTo = “othermail@yahoo.com”
$Subject = “Process not running”
$Body = “NOT RUNNING”
$SMTPServer = “smtp.gmail.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“user”, “pass”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

It's something with and but I can't figure out how exactly.

So it will be something like this: if process not running {sleep} and if second time checking not running {mail}

This should do it:

$check1 = -not ( Get-Process hl -ErrorAction SilentlyContinue )
Start-Sleep -Seconds 30
$check2 = -not ( Get-Process hl -ErrorAction SilentlyContinue )

if ($check1 -and $check2) {
    # email
}

Normally Get-Process returns either process objects, or nothing at all. In terms of truth testing, "one or more anythings" compares as $true and "no things" compares as $false .

  • -not ( get-process ) with a running process, would == $true, this makes it $false.
  • -not ( get-process ) with a stopped process, would == $false, this makes it $true.

So the if test is simple - if ($check1 -and $check2) "if this and this evaluate as $true"

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