Search code examples
powershellgoogle-chromewindows-task-scheduler

Trying to close down and re-open Google Chrome - not working


I have a requirement to close down, and re-open Google Chrome in full-screen mode (via Windows Scheduler).

The code I have is in a PowerShell script file (.ps1):

# Close Google Chrome
Get-Process chrome | ForEach-Object { $_.CloseMainWindow() | Out-Null }

# Wait for a few seconds to ensure Chrome is fully closed
Start-Sleep -Seconds 5

# Reopen Google Chrome in full-screen mode
Start-Process "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "--start-fullscreen"

It is not closing down Chrome however.

Can you see anything wrong with the code? Or is it possible to add a log to view any errors?

Thanks, Mark


Solution

    • Your code works in principle, but the .CloseMainWindow() method only requests that a target process' main window close, it doesn't enforce it.

      • Notably, the request will not be honored if:

        • A Chrome window puts up a confirmation dialog before closing.
        • A window has become unresponsive.
      • On the plus side, if the request is honored, you've allowed the processes to shut down gracefully, thereby avoiding potential data loss.

    • If you're comfortable with forcefully terminating all Chrome processes - at the risk of potential data loss - you can use Stop-Process instead, as Compo suggests:

      # Forcefully terminates all Chrome processes - RISK OF DATA LOSS
      Stop-Process -Name chrome
      

    You can combine the two approaches, if you want to give the Chrome processes a chance to shut down gracefully first, and fall back to forceful termination:

    # Try graceful shutdown first.
    $null = 
      try { (Get-Process -ErrorAction Ignore chrome).CloseMainWindow() } catch { }
    
    # Sleep a little, to see if the graceful shutdown succeeded.
    # Note: You may have to tweak the sleep intervals.
    Start-Sleep 1
    
    # If any Chrome processes still exist, terminate them forcefully now.
    if ($chromeProcesses = Get-Process -ErrorAction Ignore chrome) {
      # Terminate forcefully, and abort if that fails.
      $chromeProcesses | Stop-Process -ErrorAction Stop
      # Sleep again, to wait for the terminated processes to disappear.
      Start-Sleep 1
    }
    
    # Restart Chrome.
    # Note that with Start-Process you normally do not need the full path.
    Start-Process chrome '--start-fullscreen'
    

    Note the use of member-access enumeration to simplify the code that calls .CloseMainWindow():
    (Get-Process -ErrorAction Ignore chrome).CloseMainWindow() automatically calls .CloseMainWindow() on each process object returned by Get-Process; the try / catch enclosure ensures that no error occurs if there happen to be no matching processes, because attempting to call a method on $null would cause an error.