title: PowerShell script doesn't work correctly from Windows Task Scheduler
body: <p><strong>Overview:</strong>
  I have a script I am using to query new application requests within SCCM via WMI. The script works perfectly when launched manually within a PowerShell console (either elevated or not, doesn't matter). I need to run the script through Task Scheduler. Currently set up to run with admin credentials and the checkbox for 'Run with highest privileges' is checked.</p>
  
  <p><strong>The Issue:</strong>
  Won't run correctly from Task Scheduler within Windows Server 2008 R2. No errors are reported (task scheduler returns error code of 0) but it doesn't seem to proceed past the line that reads: </p>
  
  <pre><code>$GetAppRequest = Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_$SiteCode | Where-Object {$_.CurrentState -like "1"} | ForEach-Object {
  </code></pre>
  
  <p><strong>Here is the full script:</strong></p>
  
  <pre><code>#Hard-coded variables
  $SiteCode = "MySiteCode"
  $ComputerName = "My-SCCM-Server"
  $GUIDFilePath = "C:\Scripts\SCCM\GUIDList.txt"
  $FilePath = "C:\Scripts\SCCM"
  $smtpServers = "smtp1.domainname.com","smtp2.domainname.com"
  $reliableSmtpServer = $null
  $logpath = "C:\Scripts\SCCM\RequestLog.txt"
  
  #logging functionality
  function log($message, $type){
    $date = get-date
    $string = "$date $type : $message" | Out-File $logpath -Append
  }
  
  #does log exist?
  if (gi -Path $logpath -ErrorAction SilentlyContinue){
    #yep, the log exists!
    $logContent = cat $logpath
    log -message "Script called and log opened for writing." -type "Info"
  } else {
    #nope, the log doesn't exist, let's make one.
    write "Can't find log file, creating a new one."
    $newFileResult = New-Item -Path $logpath -ItemType File -ErrorAction Stop
    if ($newFileResult.Exists){
      log -message "new log file created" -type "Info"
    } #end if
  } #end else
  
  #Email variables
  $from = "no.reply@domainname.com"
  $to = "sccm-admin@domainname.com"
  $subject = "New SCCM Application Approval Requests"
  
  #Determine which SMTP to use.
  $smtpServers | ForEach-Object {
    if ($reliableSmtpServer -eq $null){
      if (Test-Connection -ComputerName $_ -ErrorAction SilentlyContinue){
        write "Reliable SMTP server found: $_"
        $reliableSmtpServer = $_       
      } #end if test-connection
    } #end if reliableSmtpServer exists
  } #end foreach SMTP server
  
  if ($reliableSmtpServer){
    log -message "Reliable SMTP server found, $reliableSmtpServer" -type "Info"
  } else {
    log -message "No reliable SMTP server could be found" -type "Error"
  }
  
  #Get the entries from GUIDList.txt
  if ($GetGUID = Get-Content -Path $GUIDFilePath -ErrorVariable guidReadError {
    write "Successfully read $GUIDFilePath"
    log -message "Successfully read $GUIDFilePath" -type "Info"
  } else {
    Write-Error -Message "Couldn't read GUIDfile..."
    log -message "Failed to read GUIDFile" -type "Error"
  }
  
  #Get all Application Requests with a CurrentState of "1"
  log -message 'Attempting to get all Application Requests with a CurrentState of 1' -type "Info"
  $GetAppRequest = Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_$SiteCode | Where-Object {$_.CurrentState -like "1"} | ForEach-Object {
    log -message "App found, $_.Application" -type "Info"
    if ($GetGUID -contains $_.RequestGuid) {
      Write-Host "Application request $($_.RequestGuid) already present"
      log -message "Application request $($_.RequestGuid) already present" -type "Info"
    } else {
      $appUser = $_.User
      $appName = $_.Application
      $appComment = $_.Comments
      $Body = @"
      Application request: $appName
      User: $appUser
  
      Comment: $appComment
      "@ #This row can't contain any blank spaces or tabs
  
      log -message "New record found: $appUser, $appName, $appComment" -type "Info"
  
     #Email configuration
      Send-MailMessage -SmtpServer $reliableSmtpServer -From $from -To $to -Subject $subject -Body $body -ErrorVariable mailError
     if (!($mailError)){
       write "Message successfully sent to : $to"
       log -message "Message successfully sent to : $to" -type "Info"
     } else {
       Write-Error -message "Failed to send email!"
       log -message "Failed to send email!" -type "Error"
     } #end else
  
     #Append the current objects GUID to GUIDList.txt
     Write "Appending $($_.RequestGUID) to $GUIDFilePath"
     log -message "Appending $($_.RequestGUID) to $GUIDFilePath" -type "Info"
  $_.RequestGuid | Out-File $GUIDFilePath -Append
  
    } #end else statement
  } #end forEach
  
  #Remove the GUIDList.txt file and re-create it when there's more than 100 entries
  $GUIDCount = $GetGUID.Count
  if ($GUIDCount -gt 100) {
    log -message "Greater than 100 GUID entries, clearing list." -type "Info"
    Get-Item $GUIDFilePath | Remove-Item
    New-Item -Path $FilePath -Name GUIDList.txt -ItemType file
  }
  
  #Create a new log once the log file exceeds 1000 lines.
  $logCount = $logContent.Count
  if ($logCount -gt 1000) {
    log -message "Log file is too long, removing log" -type "Warning"
    Remove-Item $logpath
  }
  </code></pre>
  
  <p><strong>Here is the scheduled task XML:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-16"?&gt;
  &lt;Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"&gt;
    &lt;RegistrationInfo&gt;
      &lt;Date&gt;2014-05-09T17:10:48.6636926&lt;/Date&gt;
      &lt;Author&gt;domainname\myUserAccount&lt;/Author&gt;
      &lt;Description&gt;Runs a script located at C:\scripts\SCCM to determine if there are any new application requests and notify IT staff via Email.&lt;/Description&gt;
    &lt;/RegistrationInfo&gt;
    &lt;Triggers&gt;
      &lt;TimeTrigger&gt;
        &lt;Repetition&gt;
          &lt;Interval&gt;PT15M&lt;/Interval&gt;
          &lt;StopAtDurationEnd&gt;false&lt;/StopAtDurationEnd&gt;
        &lt;/Repetition&gt;
        &lt;StartBoundary&gt;2014-05-09T17:12:04&lt;/StartBoundary&gt;
        &lt;ExecutionTimeLimit&gt;PT1H&lt;/ExecutionTimeLimit&gt;
        &lt;Enabled&gt;true&lt;/Enabled&gt;
      &lt;/TimeTrigger&gt;
    &lt;/Triggers&gt;
    &lt;Principals&gt;
      &lt;Principal id="Author"&gt;
        &lt;UserId&gt;domain\AdminAccount&lt;/UserId&gt;
        &lt;LogonType&gt;Password&lt;/LogonType&gt;
        &lt;RunLevel&gt;HighestAvailable&lt;/RunLevel&gt;
      &lt;/Principal&gt;
    &lt;/Principals&gt;
    &lt;Settings&gt;
      &lt;MultipleInstancesPolicy&gt;IgnoreNew&lt;/MultipleInstancesPolicy&gt;
      &lt;DisallowStartIfOnBatteries&gt;true&lt;/DisallowStartIfOnBatteries&gt;
      &lt;StopIfGoingOnBatteries&gt;true&lt;/StopIfGoingOnBatteries&gt;
      &lt;AllowHardTerminate&gt;true&lt;/AllowHardTerminate&gt;
      &lt;StartWhenAvailable&gt;false&lt;/StartWhenAvailable&gt;
      &lt;RunOnlyIfNetworkAvailable&gt;false&lt;/RunOnlyIfNetworkAvailable&gt;
      &lt;IdleSettings&gt;
        &lt;StopOnIdleEnd&gt;true&lt;/StopOnIdleEnd&gt;
        &lt;RestartOnIdle&gt;false&lt;/RestartOnIdle&gt;
      &lt;/IdleSettings&gt;
      &lt;AllowStartOnDemand&gt;true&lt;/AllowStartOnDemand&gt;
      &lt;Enabled&gt;true&lt;/Enabled&gt;
      &lt;Hidden&gt;false&lt;/Hidden&gt;
      &lt;RunOnlyIfIdle&gt;false&lt;/RunOnlyIfIdle&gt;
      &lt;DisallowStartOnRemoteAppSession&gt;false&lt;/DisallowStartOnRemoteAppSession&gt;
      &lt;UseUnifiedSchedulingEngine&gt;false&lt;/UseUnifiedSchedulingEngine&gt;
      &lt;WakeToRun&gt;false&lt;/WakeToRun&gt;
      &lt;ExecutionTimeLimit&gt;P3D&lt;/ExecutionTimeLimit&gt;
      &lt;Priority&gt;7&lt;/Priority&gt;
    &lt;/Settings&gt;
    &lt;Actions Context="Author"&gt;
      &lt;Exec&gt;
        &lt;Command&gt;powershell.exe&lt;/Command&gt;
        &lt;Arguments&gt;-noprofile -file "C:\scripts\sccm\Notify.ps1"&lt;/Arguments&gt;
      &lt;/Exec&gt;
    &lt;/Actions&gt;
  &lt;/Task&gt;
  </code></pre>