title: Powershell issue with executing in Task Scheduler
body: <p>I have below script that add users to o365 group at start of their work as below:</p>
  <pre><code>$DateMaxTime = (Get-date).AddDays(0)
  $DateMaxTimeNew = (Get-date).AddDays(-30)
  
  $usersRO = Get-ADUser -Filter * -Properties * -SearchBase &quot;OU=Users,OU=Resources,OU=Romania,OU=DataManagement,DC=USA&quot;|where {$_.Description -like &quot;*TEMP*&quot; -or $_.Description -like &quot;*PERM*&quot; } |select samaccountname,description,name
  $groupsRO = '#O365-EXTERNALACCESS'
  
  
  $FinalResultRO = New-object System.Collections.ArrayList
  
  ForEach($groupRO in $groupsRO){
  $membersRO = Get-ADGroupMember -Identity $groupRO -Recursive | Select -ExpandProperty samaccountname
  Foreach ($userRO in $usersRO){
  $AcountNameRO = $userRO.samaccountname
  $DatePartRONew = get-aduser -identity $AcountNameRO -Properties * | Select-Object whenCreated
  $DatePartSubsRONew = $DatePartRONew.whenCreated
  $DataPartROdesc=$userRO.description
  $expressionRO = ([regex]'(\d{2}/\d{2}/\d{4})').Match($DataPartROdesc).Groups[0].Value
  $DatePartRO= $expressionRO
  $FinalDateRO = [datetime]::ParseExact($DatePartRO,'dd/MM/yyyy',$null)
      If ($DatePartSubsRONew -lt $DateMaxTimeNew){
      Write-Host &quot;$AcountNameRO ouf of date scope&quot;}
      else {Write-Host &quot;$AcountNameRO in scope&quot;
          If ((get-date $FinalDateRO.Date) -eq (get-date $DateMaxTime.Date)){
              Write-Host &quot;$AcountNameRO is a today Starter&quot;
              If ($membersRO -notcontains $AcountNameRO ) {
              Write-Host &quot;Adding external group $groupRO for: $AcountNameRO&quot;
              Add-ADGroupMember -Identity &quot;#O365-EXTERNALACCESS&quot; -Members $AcountNameRO 
              $FinalResultRO.Add((New-Object psobject -Property @{User=$AcountNameRO}))
               } 
              Else {Write-Host &quot;$AcountNameRO  exists in  group $groupRO&quot;}
          }Else {Write-Host &quot;$AcountNameRO is not a Starter&quot;}
          }
      }
  }
  
  $listRO = [array]$FinalResultRO |Select User |Out-String
  $listRO.gettype()
  
  if [string]::IsNullOrEmpty($listRO){
  Write-Host &quot;nothing to send&quot;
  }
  Else {
  Write-Host &quot;Mail sent&quot;
  Send-MailMessage -From &quot;mail1@donut.com&quot; -To &quot;mail2@donut.com&quot; -Subject &quot;Following users have been granted external access rights&quot; -smtpServer &quot;donut&quot; -body &quot;$($listRO)&quot;
  }
  </code></pre>
  <p>I run this script daily in task scheduler with higest privilage .</p>
  <p>For some reasons, sometimes when script is executing , telling me that users has been added to group but its not changing in Active DIrectory . Only when I run the script second time its working (manually on powershell , not using task scheduler).</p>
  <p>What can be a reason for this ?</p>