title: Running Powershell script from Task Scheduler on Remote Desktop while Logged Off
body: <p>I have a powershell script that I'm trying to get to work on a remote desktop while logged off. I have, so far, been able to get this script to run successfully on my local machine with the task scheduler set to both of the following security settings: "Run only when user is logged on" and "Run whether user is logged on or not."</p>
  
  <p>Once I got that working I went to the remote desktop and created a scheduled task there. When set to "Run only when user is logged on," the script runs as intended - just like it did on my local machine. When I switch to "Run whether user is logged on or not" (with "Run with highest privileges" selected), the script no longer runs. </p>
  
  <p>I don't get any errors or messages indicating that my security level on the remote desktop is an issue, so I'm not sure if that's the cause or how to change it if it is.</p>
  
  <p>Does anyone know how I can resolve this issue?</p>
  
  <pre><code># collect excel process ids before and after new excel background process is started
  $priorExcelProcesses = Get-Process -name "*Excel*" | % { $_.Id }
  $Excel = New-Object -ComObject Excel.Application
  $postExcelProcesses = Get-Process -name "*Excel*" | % { $_.Id }
  
  #run program
  
  #manually map network drive
  if (-Not (Test-Path 'I:\')) {New-PSDrive -Name "I" -PSProvider FileSystem -Root "\\MyServer\MyShare"}
  
  $folderPath = "\\MyServer\MyShare\rest of file path"
  $filePath = "MyServer\MyShare\rest of file path\filename.xlsm"
  $tempPath = "C:\Users\Public"
  $tempFile = "C:\Users\Public\filename.xlsm"
  
  #copy file from I drive to remote desktop
  Copy-Item -Path $filePath -Destination $tempPath
  
  #create Excel variables
  $excel = new-object -comobject excel.application
  $excel.visible = $False
  $excelFiles = Get-ChildItem -Path $tempPath -Include *.xls, *xlsm -Recurse
  
  #open excel application and run routine
  Foreach($file in $excelFiles)
  {
      $workbook = $excel.workbooks.open($tempFile)
      $worksheet = $workbook.worksheets.item(1)
      $excel.Run("getAccessData")
      $workbook.save()
      $workbook.close()
  }
  
  #copy file from remote desktop back onto I drive
  Copy-Item -Path $tempFile -Destination $folderPath
  
  # try to gently quit
  $Excel.Quit()
  [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
  
  # otherwise allow stop-process to clean up
  $postExcelProcesses | ? { $priorExcelProcesses -eq $null -or $priorExcelProcesses -notcontains $_ } | % { Stop-Process -Id $_ }
  </code></pre>