如何检查 Powershell 中进程是否正常运行?

如何检查 Powershell 中进程是否正常运行?

我正在编写一些 powershell 来检查 Google Drive for Desktop 进程是否正在运行。如果正在运行,我需要停止它并重新启动它。我无法理解如果驱动器进程未运行,如何避免抛出错误:

$drive = Get-Process -Name "GoogleDriveFS"

如果不是,我该如何检查进程是否以不会引发错误的方式运行?

#Get Drive Process
$drive = Get-Process -Name "GoogleDriveFS"
write $drive\n

if ($drive) {
    #Stop Drive
    $drive | Stop-Process

    write "Drive Process info1 : " $drive

    #Wait 5 Seconds
    sleep 5

    #Check to see if Drive closed
    #If not, then force close
    if (!$drive.HasExited) {
        $drive | Stop-Process -Force

        #Wait 5 Seconds
        sleep 5
        write "Drive Process info2 : " $drive
    }

    #Check again
    #If not running, start Drive
    else {
        #Start Drive
        write "Google Drive is not running, Starting Google Drive..."
        Start-Process  "C:\Program Files\Google\Drive File Stream\[0-9]*.*\GoogleDriveFS.exe"

        #check
        write $drive
    }
}

答案1

添加-ErrorAction SilentlyContinue到您的Get-Process命令。

您已经隐式测试了$null,所以应该没问题。

PS C:\Users\rpresser> $x = get-process -name "fnord" -ErrorAction SilentlyContinue
PS C:\Users\rpresser> $x -eq $null
True

相关内容