title: Add User to Local Group
body: <p>This function should run on Windows Server 2003 and 2008 R2
  Using the command line to execute it line by line is SUCCESSFULL! Execution by script fails.</p>
  
  <pre><code>function addUser2Group([string]$user,[string]$group)
  {    
      $cname = gc env:computername
      $objUser = [ADSI]("WinNT://$user")
      $objGroup = [ADSI]("WinNT://$cname/$group,group")  
      $members = $objGroup.PSBase.Invoke('Members')
      $found = $false
  
      foreach($m in $members)
      {
          if($m.GetType().InvokeMember('Name', 'GetProperty', $null, $m, $null) -eq $user)
          {
              $found = $true
          }
      }
  
      if(-not $found)
      {
          $objGroup.PSBase.Invoke('Add',$objUser.PSBase.Path)
      }
  
      $members = $objGroup.PSBase.Invoke('Members')
      $found = $false
      foreach($m in $members)
      {
          if($m.GetType().InvokeMember('Name', 'GetProperty', $null, $m, $null) -eq $user)
          {
              $found = $true
          }
      }
  
      return $found
  }
  
  addUser2Group('MyGlobalMonitoringUser',"SomeDBGroup")
  </code></pre>
  
  <p>It should add a user to a local group. But it only gives me the following error:</p>
  
  <pre><code>Exception calling "Invoke" with "2" argument(s): "Unknown error (0x80005000)"
  +     $members = @($objGroup.PSBase.Invoke &lt;&lt;&lt;&lt; ("Members"))
  + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  + FullyQualifiedErrorId : DotNetMethodException
  </code></pre>
  
  <p><br><br><br><br>
  Edit: the error message that occurs with /add is</p>
  
  <pre><code>The following exception occurred while retrieving member "Add": "Unknown error (0x80005000)"
  </code></pre>
  
  <p><br>
  Code is:</p>
  
  <pre><code>function addUser2Group([string]$user,[string]$group)
  {
      $cname = gc env:computername
      try
      {
          ([adsi]"WinNT://$cname/$group,group").Add("WinNT://$cname/$user,user")
      }
      catch
      {
          write2log($_)
          return $false
      }
  
      return $true
  }
  </code></pre>