PowerShell script using Bits-Transfer does not work as Scheduled Task

bitspowershellscheduled-task

I've tried utilizing other Q/A's such as Windows Server 2008 R2 PowerShell script runs manually, but not as a scheduled task but to no avail.

Basically I've got a PoSh script (apparently that's the hot abbreviation for it nowadays) that copies a lot of large files, one at a time, from one server (UNC path) to the local drive. It does this in a loop, and it uses BITS Transfer. Roughly:

  1. Start-BitsTransfer source/destination/asynchronous/low-priority
  2. while that Bits job's state is still "connecting" or "transferring", Sleep 2 seconds (i.e. wait for it to finish)
  3. Once we're out of that loop, Complete-BitsTransfer
  4. Write-Host a "completed file X" msg
  5. get the next file, repeat… (so yes, there's an outer loop over the file-list obtained from Get-ChildItem)

The script works when run from PoSh ISE, and regular PoSh console.

I've tried using Sleep, Start-Sleep, and even [Threading.Thread]::Sleep, thinking that that was the problem. Then I wrapped the .ps1 in a .bat and, when run from CMD, that works too. But in all cases, the Schedule Task, whether calling the .ps1 directly or the wrapper .bat, fails.

It says it's succeeding, but what's really happening is it starts all the transfer jobs, they get into a "Suspended" state (shown by Get-BitsTransfer in the PoSh window), and the task thinks everything's fine and finishes, leaving these orphaned BITS jobs that I can't even Complete-BitsTransfer on b/c they throw an error from that too.

Other behaviors:

  • The above is what happens when I run it as my domain-admin account & let it store the pwd w/ the task.
  • If I change it to a service account (which is an admin on the box), it actually never starts the BITS jobs at all. It also throws the error "the user must have 'log on as batch job' rights".
  • If I try to let it run as a local/builtin account, it also fails to start the BITS jobs.

Tearing my hair out here… help!

Best Answer

According to MS the scheduled task has to be run under an interactive logon.

https://msdn.microsoft.com/en-us/library/windows/desktop/ee663885(v=vs.85).aspx