title: Powershell script cannot access a file when run as a Scheduled Task
body: <p>My Powershell (2.0) script has the following code snippet:</p>
  
  <pre><code>$fileName = "c:\reports\1.xlsx"
  $xl = new-object -comobject excel.application
  $xlFormat = [Microsoft.Office.Interop.excel.XlFileFormat]::xlWorkbookDefault
  $xl.displayalerts = $false
  $workbook = $xl.workbooks.open($fileName)
  #Code to manipulate a worksheet
  $workbook.SaveAs($fileName, $xlformat)
  $xl.quit()
  $error | out-file c:\reports\error.txt
  </code></pre>
  
  <p>I can run this script in the Powershell command prompt with no issues. The spreadsheet gets updated, and error.txt is empty. However, when I run it as a task in Task Scheduler, I get errors with the first line.</p>
  
  <blockquote>
    <p>Exception calling "Open" with "1" argument(s): "Microsoft Office Excel cannot access the file 'C:\reports\1.xlsx'. There are several possible reasons:
    The file name or path does not exist.
    The file is being used by another program.
    The workbook you are trying to save has the same name as a currently open workbook.</p>
  </blockquote>
  
  <p>I run the task with the same credentials I use to run the script in the Powershell command prompt. When I run the script manually, it can open, update, and save the spreadsheet with no issues. When I run it in Task Scheduler, it can't access the spreadsheet.</p>
  
  <p>The file in question is readable/writeable for all users. I've verified I can open the file in Excel with the same credentials. If I make a new spreadsheet and put its name in as the $filename, I get the same results. I've verified that there are no instances of Excel.exe in Task Manager. </p>
  
  <p>Oddly, if I use get-content, I don't have any problems. Also, if I make a new spreadsheet, I don't have any problem.</p>
  
  <pre><code>$fileName = "c:\reports\1.xlsx"
  $xl = get-content $spreadsheet
  $xl = new-object -comobject excel.application
  $xlFormat = [Microsoft.Office.Interop.excel.XlFileFormat]::xlWorkbookDefault
  $xl.displayalerts = $false
  # Commented out $workbook = $xl.workbooks.open($fileName)
  $workbook = $xl.workbooks.add()
  #Code to manipulate a worksheet
  $workbook.SaveAs($fileName, $xlformat)
  $xl.quit()
  $error | out-file c:\reports\error.txt
  </code></pre>
  
  <p>That works fine. So Get-ChildItem can open the file with no issue. ComObject can open the file if I run it manually, but not if it's run as task. </p>
  
  <p>I'm at a loss. Any ideas?</p>