首页 文章

计划的Powershell任务未被执行

提问于
浏览
0

我在Task Scheduler上添加了powershell脚本任务,将用户帐户设置为Admin,然后将选项设置为“仅在用户登录时运行” .

当我手动运行此任务时,它正确执行,但是当我将选项设置为“运行是否登录用户”时,它会执行但从未成功完成任务 .

在两种方案中都启用了“以最高权限运行” . 似乎正在发生什么?如何在不需要登录的情况下运行任务?

编辑:

脚本将文件从已装入的驱动器复制到本地目录 . 当我使用Powershell而不是任务调度程序逐行运行脚本时,它可以正常运行(在正常和高级Powershell上) .

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

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

和任务调度程序:Powershell -Command“c:\ scripts \ my_script.ps1”

1 回答

  • 0

    对于错误记录,需要将脚本拆分为更易于管理的块 . 单线程用于交互式会话,但不易维护 .

    $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
    }
    

相关问题