title: How to find out when a service was restarted using Powershell
body: <p>I have a Powershell script as below using which i want to find out the uptime of a service. </p>
  
  <p>This script is able to successfully capture the uptime of service if there is a reboot of the machine itself or stop/start of the service.</p>
  
  <p>But when the service is stopped, it doesn't capture the correct time since when it was stopped and still i'm getting the uptime as since when the machine was rebooted. </p>
  
  <p>Any help? Thanks in advance!</p>
  
  <pre><code>function Get-ServiceUptime
  {
    param([string]$Name)
  
    # Prepare name filter for WQL
    $Name = $Name -replace "\\","\\" -replace "'","\'" -replace "\*","%"
  
    # Fetch service instance
    $Service = Get-CimInstance -ClassName Win32_Service -Filter "Name LIKE '$Name'"
  
    # Use ProcessId to fetch corresponding process
    $Process = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $($Service.ProcessId)"
  
    # Calculate uptime and return
    return (Get-Date) - $Process.CreationDate
  }
  
  $uptime = Get-ServiceUptime -Name MyServiceName
  </code></pre>