1

I'm writing some powershell to check if the Google Drive for Desktop process is running. If it is, I need to stop it and restart it. I'm having trouble understanding how to avoid throwing errors if the drive process isn't running with the line:

$drive = Get-Process -Name "GoogleDriveFS"

How would I check to see if the process is running in a way that won't throw errors if it's not?

#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
    }
}
g1Lg4m3sh
  • 21
  • 1
  • 4

1 Answers1

1

Add -ErrorAction SilentlyContinue to your Get-Process command.

You're already implicitly testing for $null, so that should be fine.

PS C:\Users\rpresser> $x = get-process -name "fnord" -ErrorAction SilentlyContinue
PS C:\Users\rpresser> $x -eq $null
True
Ross Presser
  • 1,401
  • 1
  • 13
  • 19
  • 1
    Ahh. Thanks! That got it. I also realized that my else statement was inside the if. I've been spending too much time in C++ lol – g1Lg4m3sh Oct 19 '21 at 18:29