title: Getting Processes via Get-Counter does not refresh when processes change and throws errors if processes end
body: <p>My script monitors the CPU usage of the process, looping the code every 5 sec and writing it to a file. Which works fine.</p>
  
  <p>But I found when a new Process runs my script will not find it until I stop the script and rerun it again.</p>
  
  <p>Also if a process ends/stops, the script give an this error:</p>
  
  <blockquote>
    <p>Get-Counter : The data in one of the performance counter samples is
    not valid.   View the Status property for each
    PerformanceCounterSample object to make sure it  contains valid data.</p>
    
    <p>At line:2 char:34</p>
  </blockquote>
  
  <p>It seems PowerShell retrieves the Process information only once and caches it.</p>
  
  <p>If I run the bellow script (which is a part of all my script), it runs perfectly:</p>
  
  <pre><code>while($true) {
       $ProcessId = (Get-Counter "\Process(*)\ID Process").CounterSamples
       $ProcessId.count
       Start-Sleep -s 5
  }
  </code></pre>
  
  <p>If I have 50 process it will gives 50, but if a new process starts it will keep giving 50 until I restart the script.</p>
  
  <p>If I stop any process it will give the same error above.  </p>
  
  <p>Any idea how to solve this problem and force PowerShell to reread the process list without restarting the script?</p>