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 }
} 1 1 Answer
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 1