确定进程是否正在运行

时间:2013-12-03 15:50:43

标签: powershell blat

所有

我是Power Shell脚本的新手,我的第二个脚本不能100%正常工作。我不确定发生了什么。

目的:

  1. 检查特定进程是否正在运行。
  2. 如果正在运行,请发送电子邮件通知。
  3. 如果未运行,请尝试启动该过程。
  4. 如果尝试启动该过程,请重新检查过程是否已开始。
  5. 问题:

    • 如果我更改脚本的目录位置(以确保它是错误的),我会收到正确的电子邮件。
    • 如果流程正在运行,我会收到正确的电子邮件。
    • 如果进程没有运行,脚本会正确启动进程,但会发送并发送电子邮件,说明进程在运行时没有运行。

    脚本:

    # Date and Date/Time stamping for files and logs.
    $FileDateTimeStamp = get-date -uformat "%m%d%Y-%H%M%S"
    $FileDateStamp = get-date -uformat "%m%d%Y"
    
    # Logs directory.
    $LogsDirectory = "C:\logs\"
    
    # AS2 file information.
    $AS2 = "C:\Program Files\nsoftware\AS2 Connector V2\as2app\bin\nsoftware.AS2Connector.exe"
    $AS2ParentDirectory = "C:\Program Files\nsoftware\AS2 Connector V2"
    $ProcessNameToCheck = "nsoftware.AS2Connector"
    $ProcessIsRunning = Get-Process $ProcessNameToCheck -ErrorAction SilentlyContinue
    $StartTheProcess = start-process -filepath $AS2
    $SleepTime = 2
    
    # Exchange information for sending emails.
    $EmailServer = "email.me.com"
    $EmailFrom = "me@me.com"
    $AuthUser = "username"
    $AuthPass = "password"
    $EmailPort = 25
    $MaxRetries = 1
    
    # Blat log file location/name.
    $BlatLogFile = $LogsDirectory + "BlatLog-" + $FileDateStamp + ".log"
    
    # Blat information.
    #$EmailTo = "smaguire@varietydistributors.com,abarnes@varietydistributors.com,tmalcom@varietydistributors.com"
    $EmailTo = "smaguire@varietydistributors.com"
    $EmailToSubjectSuccess = "AS2 Connector is running."
    $EmailToBodySuccess = "The process check for AS2 Connector on OSPC was successful. AS2 Connector is running."
    $EmailToSubjectFail = "AS2 Connector is NOT running."
    $EmailToBodyFail = "The process check for AS2 Connector on OSPC was unsuccessful. Attempted to start the application which was also unsuccessful. AS2 Connector is NOT currently running on OSPC."
    $EmailToSubjectNotInstalled = "AS2 Connector Installation Not Found."
    $EmailToBodyNotInstalled = "The process check for AS2 Connector on OSPC failed because AS2 Connector does not seem to be installed."
    $XHeaderInfo = "Email sent from OSPC"
    
    function WriteLogFile {
        #Code snippet obtained from: http://poshcode.org/2566
    
        [cmdletbinding()]
        Param(
            [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()]
            [string] $Message,
    
            [Parameter()] [ValidateSet(“Error”, “Warn”, “Info”)]
            [string] $Level = “Info”,
    
            [Parameter()] [ValidateRange(1,30)]
            [Int16] $Indent = 0,
    
            [Parameter()]
            [IO.FileInfo] $ScriptLogFile = $LogsDirectory + "ScriptLog-" + $FileDateStamp + ".log",
    
            [Parameter()]
            [Switch] $Clobber,
    
            [Parameter()]
            [String] $EventLogName,
    
            [Parameter()]
            [String] $EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name,
    
            [Parameter()]
            [Int32] $EventID = 1
        )
    
        Begin {}
    
        Process {
            try {           
                $msg = '{0}{1} : {2} : {3}' -f (" " * $Indent), (Get-Date -Format “yyyy-MM-dd HH:mm:ss”), $Level.ToUpper(), $Message
    
                switch ($Level) {
                    'Error' { Write-Error $Message }
                    'Warn' { Write-Warning $Message }
                    'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor White}
                }
    
                if ($Clobber) {
                    $msg | Out-File -FilePath $ScriptLogFile
                } else {
                    $msg | Out-File -FilePath $ScriptLogFile -Append
                }
    
                if ($EventLogName) {
                    if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) { 
                        [Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName) 
                    } 
                    $log = New-Object System.Diagnostics.EventLog  
                    $log.set_log($EventLogName)  
                    $log.set_source($EventSource) 
    
                    switch ($Level) {
                        “Error” { $log.WriteEntry($Message, 'Error', $EventID) }
                        “Warn”  { $log.WriteEntry($Message, 'Warning', $EventID) }
                        “Info”  { $log.WriteEntry($Message, 'Information', $EventID) }
                    }
                }
            } catch {
                throw “Failed to create log entry in: ‘$ScriptLogFile’. The error was: ‘$_’.”
            }
        }
    
        End {}
    }
    
    if (test-path $AS2ParentDirectory) {
        # AS2 is installed on this machine.
        # Check for the running process.
        if (!($ProcessIsRunning)) {
            # Process is not found = not runing.
            # Try to start the process.
            # Once start attempt is complete, recheck to make sure failed or succeeded.
            # Failed: send an alert email through blat.
            # Succeeded: Send an alert email through blat.
            write-host "AS2 Connector is not running. Attempting to start."
            WriteLogFile -message "Script Line #142: AS2 Conenctor is not running. Attempting to start." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            $StartTheProcess
    
            # Give the process a little time to start before checking. Wait X seconds.
            write-host "Going to sleep for $SleepTime seconds."
            WriteLogFile -message "Script Line #147: Going to sleep for $SleepTime seconds." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            start-sleep -s $SleepTime
    
                # Now, let's go ahead and recheck to see if the process started or not.
                if (!($ProcessIsRunning)) {
                    # Process did not start successfully.
                    write-host "AS2 Connector did not start successfully. Sending an email to advise."
                    WriteLogFile -message "Script Line #162: AS2 Conenctor did not start successfully. Sending an email to advise." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    WriteLogFile -message "Sending an email to: $EmailTo" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    WriteLogFile -message "Email Subject: $EmailToSubjectFail" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    WriteLogFile -message "Email Body: $EmailToBodyFail" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    C:\blat\blat.exe -to $EmailTo -s $EmailToSubjectFail -i $EmailFrom -body $EmailToBodyFail -server $EmailServer -f $EmailFrom -u $AuthUser -pw $AuthPass -port $EmailPort -try $MaxRetries -debug -log $BlatLogFile -timestamp -x $XHeaderInfo
                } else {
                    # Process started successfully.
                    write-host "AS2 Connector started successfully. Sending an email to advise."
                    WriteLogFile -message "Script Line #154: AS2 Conenctor started successfully. Sending an email to advise." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    WriteLogFile -message "Sending an email to: $EmailTo" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    WriteLogFile -message "Email Subject: $EmailToSubjectSuccess" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    WriteLogFile -message "Email Body: $EmailToBodySuccess" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
                    C:\blat\blat.exe -to $EmailTo -s $EmailToSubjectSuccess -i $EmailFrom -body $EmailToBodySuccess -server $EmailServer -f $EmailFrom -u $AuthUser -pw $AuthPass -port $EmailPort -try $MaxRetries -debug -log $BlatLogFile -timestamp -x $XHeaderInfo            
                }
        } else {
            # Process is found = running.
            # Send an email advising of running status.
            write-host "Verified AS2 Connector is running. Sending an email to advise."
            WriteLogFile -message "Script Line #130: Verified AS2 Conenctor is running. Sending an email to advise." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Sending an email to: $EmailTo" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Email Subject: $EmailToSubjectSuccess" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Email Body: $EmailToBodySuccess" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            C:\blat\blat.exe -to $EmailTo -s $EmailToSubjectSuccess -i $EmailFrom -body $EmailToBodySuccess -server $EmailServer -f $EmailFrom -u $AuthUser -pw $AuthPass -port $EmailPort -try $MaxRetries -debug -log $BlatLogFile -timestamp -x $XHeaderInfo
        }
    } else {
        # AS2 is not installed on this machine.
        # Send an email advising that there is a potential problem.
        write-host "AS2 Connector does not seem to be installed or is corrupt. Sending an email to advise."
        WriteLogFile -message "Script Line #173: AS2 Conenctor does not seem to be installed or is corrupt. Sending an email to advise." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
        WriteLogFile -message "Sending an email to: $EmailTo" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
        WriteLogFile -message "Email Subject: $EmailToSubjectNotInstalled" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
        WriteLogFile -message "Email Body: $EmailToBodyNotInstalled" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
        C:\blat\blat.exe -to $EmailTo -s $EmailToSubjectNotInstalled -i $EmailFrom -body $EmailToBodyNotInstalled -server $EmailServer -f $EmailFrom -u $AuthUser -pw $AuthPass -port $EmailPort -try $MaxRetries -debug -log $BlatLogFile -timestamp -x $XHeaderInfo
    }
    

    出错的代码部分是:

        # Now, let's go ahead and recheck to see if the process started or not.
        if (!($ProcessIsRunning)) {
            # Process did not start successfully.
            write-host "AS2 Connector did not start successfully. Sending an email to advise."
            WriteLogFile -message "Script Line #162: AS2 Conenctor did not start successfully. Sending an email to advise." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Sending an email to: $EmailTo" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Email Subject: $EmailToSubjectFail" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Email Body: $EmailToBodyFail" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            C:\blat\blat.exe -to $EmailTo -s $EmailToSubjectFail -i $EmailFrom -body $EmailToBodyFail -server $EmailServer -f $EmailFrom -u $AuthUser -pw $AuthPass -port $EmailPort -try $MaxRetries -debug -log $BlatLogFile -timestamp -x $XHeaderInfo
        } else {
            # Process started successfully.
            write-host "AS2 Connector started successfully. Sending an email to advise."
            WriteLogFile -message "Script Line #154: AS2 Conenctor started successfully. Sending an email to advise." -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Sending an email to: $EmailTo" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Email Subject: $EmailToSubjectSuccess" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            WriteLogFile -message "Email Body: $EmailToBodySuccess" -level Info -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "AS2Check.ps1"
            C:\blat\blat.exe -to $EmailTo -s $EmailToSubjectSuccess -i $EmailFrom -body $EmailToBodySuccess -server $EmailServer -f $EmailFrom -u $AuthUser -pw $AuthPass -port $EmailPort -try $MaxRetries -debug -log $BlatLogFile -timestamp -x $XHeaderInfo            
        }
    

2 个答案:

答案 0 :(得分:4)

$ProcessIsRunning = Get-Process $ProcessNameToCheck -ErrorAction SilentlyContinue
$StartTheProcess = start-process -filepath $AS2

运行这些行时,命令立即执行,结果存储在变量中。因此,如果进程未在脚本开头运行,$ProcessIsRunning将始终为null(未运行)。

解决方案是删除顶部的两行,并在脚本中替换以下变量的每个实例:

  • $ProcessIsRunning(Get-Process $ProcessNameToCheck -ErrorAction SilentlyContinue)。防爆。 if(!(Get-Process $ProcessNameToCheck -ErrorAction SilentlyContinue)) { "not running" } else { "running" }

  • $StartTheProcessStart-Process -Filepath $AS2

您也可以尝试这种方法,这可能是您最初的计划:

$ProcessIsRunning = { Get-Process notepad -ErrorAction SilentlyContinue }
$StartTheProcess = { Start-Process notepad }

#Run the start-process command
$StartTheProcess.Invoke()

#This will run the get-process command whenever you call it by using the Invoke() method.
if(!$ProcessIsRunning.Invoke()) {
    "Not running"
} else {
    "Running"
}

输出继电器:

Running

答案 1 :(得分:0)

$StartTheProcess = start-process -filepath $AS2保存运行启动过程的结果。如果脚本中有一行代码$StartTheProcess(正如您所做),则不要指望它运行命令;它只会显示最初保存的输出。

在适当的位置拨打start-process,或使用功能。

编辑:正如评论所说,(我错过了)你还需要重新检查进程是否正在运行。在第二次检查之前重新运行此行。

$ProcessIsRunning = Get-Process $ProcessNameToCheck -ErrorAction SilentlyContinue