简体   繁体   中英

Scheduled Powershell task not being executed

I added a powershell script task on the Task Scheduler, set the user account to an Admin, then set the option to "Run only when user is logged on".

When I run this task manually, it executes correctly, but when I set the option to "Run whether user is logged on or not" it executes but never completes the task successfully.

"Run with highest privileges" is enabled on both scenario. What seems to be happening? How do I run the task without needing to be logged on?

EDIT:

Script copies file from a mounted drive to a local directory. When I run the script line by line using Powershell instead of the task scheduler, it works (both on normal and elevated Powershell).

$currentDate = (Get-Date).AddDays(-1).ToString('yyyyMMdd');

gci "C:\some_directory" | where-object { ($_.Name -match $currentDate) -and (! $_.PSIsContainer) } | Copy-Item -Destination "Y:\" -force;

and on task scheduler: Powershell -Command "c:\\scripts\\my_script.ps1"

For error logging, the script needs to be splitted into more manageable chunks. An one-liner is hady for interactive sessions but are not easy for maintenance.

$currentDate = (Get-Date).AddDays(-1).ToString('yyyyMMdd')
$log = "c:\temp\logfile.txt"
$errorCount = $Error.Count

# Save the source files into an array
$files = @(gci "C:\some_directory" | ? {
  ($_.Name -match $currentDate) -and (! $_.PSIsContainer) 
})

# Log about source to see if $files is empty for some reason    
Add-Content $log $("Source file count: {0}" -f $files.Count)
# Check that Y: drive is available
Add-Content $log $("Testing access to destination: {0}" -f (test-path "y:\") )

$files | % {
  # Check the error count for new errors and log the message
  if($Error.Count -gt $errorCount) {
    Add-Content $log $Error
    $errorCount = $Error.Count
  }
  Copy-Item $_.FullName -Destination $(join-path "y:" $_.Name) -force
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM