【问题标题】:Scheduled Powershell task not being executed未执行计划的 Powershell 任务
【发布时间】:2013-10-11 03:56:50
【问题描述】:

我在任务计划程序上添加了一个 powershell 脚本任务,将用户帐户设置为管理员,然后将选项设置为“仅在用户登录时运行”。

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

在两种情况下都启用了“以最高权限运行”。似乎发生了什么?如何在无需登录的情况下运行任务?

编辑:

脚本将文件从已安装的驱动器复制到本地目录。当我使用 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"

【问题讨论】:

  • 你能添加脚本的作用吗?
  • 嗨,我已经更新了我的帖子。
  • 将日志语句添加到脚本中,以便查看它在哪一步失败。使用Write-Eventlog 登录事件日志或使用Add-Content 登录文件。
  • @vonPryz 嗨,我正在做 gc ... |哪里... |我可以在其中添加 write-eventlog 吗?
  • 编辑您的帖子并显示脚本。

标签: powershell scheduled-tasks windows-server-2008-r2 powershell-1.0


【解决方案1】:

对于错误记录,脚本需要拆分成更易于管理的块。 one-liner 非常适合交互式会话,但不容易维护。

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

【讨论】:

  • Copy-Item $_ -Destination "y:\" -force 在脚本文件夹中搜索文件而不是 C:\some_directory。我是 powershell 的新手,所以我该如何做 Copy-Item $directory + $filename -Destination "Y:\" -force
  • @Bahamut,查看更新的Copy-Item 命令,该命令使用 FullName 和 Name 属性。
猜你喜欢
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多