title: Ensure that IIS AppPool user is added to windows group
body: <p>I am trying to deploy an ASP.NET application to IIS using Powershell (run by Ansible).</p>
  
  <p>I want my application to be able to query the performance counters so I am adding it to the Performance Monitor Users using this Powershell script:</p>
  
  <pre><code>appPoolName=$args[0]
  
  $group = [ADSI]"WinNT://$Env:ComputerName/Performance Monitor Users,group"
  
  $ntAccount = New-Object System.Security.Principal.NTAccount("IIS AppPool\$appPoolName")
  $strSID = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier])
  $user = [ADSI]"WinNT://$strSID"
  
  $group.Add($user.Path)
  </code></pre>
  
  <p>It actually comes from another SO question: <a href="https://stackoverflow.com/questions/18208890/add-iis-apppool-asp-net-v4-0-to-local-windows-group">Add IIS AppPool\ASP.NET v4.0 to local windows group</a>.</p>
  
  <p>After the deployment, it can happen that the user is added to the group but the application still can't access the performance counters.</p>
  
  <p>The script is run just before starting the App Pool and the application.
  I have tried the following things, without success:</p>
  
  <ul>
  <li>Restart the application</li>
  <li>Restart the App Pool</li>
  <li><a href="https://stackoverflow.com/questions/39527233/iis-apppool-user-permissions-not-working">Set AnonymousAuthentication to 'Application pool identity'</a></li>
  <li>Deploy again</li>
  </ul>
  
  <p>I have modified my deployment scripts in the following ways, without success:</p>
  
  <ul>
  <li>Remove the user from the group before adding it</li>
  <li>Restart the App Pool after adding the user. IIS actually complains ("The service cannot accept messages at this time").</li>
  <li>Add the user to the group after starting the application</li>
  <li>Add the user to the group at the beginning of the deploy (before stopping the application and pool)</li>
  </ul>
  
  <p>The only way I have to solve my problem is to restart the machine. I would like to know if there is a better one!</p>
  
  <p>If it is possible, I think making the App Pool user log off and back on would solve my problem. I haven't found how to do that (restarting or recycling the App Pool doesn't work).</p>