jaz*_*Box 3 windows powershell scheduled-tasks
我对 Powershell 脚本很陌生,但曾尝试修改我在此处找到的脚本,以在 Windows 2012 R2 中使用 Powershell 导入一些 XML 计划任务。
我已成功使用此脚本将计划任务导入根 [任务计划程序库]。
问题似乎是计划任务需要导入到任务计划程序库下的子文件夹中,我们说“子任务”
$task_path = "C:\Users\me\Desktop\ST Testing\exported ST's\scheduledTask.xml"
$task_user = "usr"
$task_pass = "pwd"
$schedule = new-object -com("Schedule.Service")
$schedule.Connect("server") # servername
#$folder = $schedule.GetFolder("\") <===This works fine
$folder = $schedule.GetFolder("\SubTasks") #<===This does not work
Write-Host $folder
Get-Item $task_path | % {
$task_name = $_.Name.Replace('.xml', '')
$task_xml = Get-Content $_.FullName
$task = $schedule.NewTask($null)
$task.XmlText = $task_xml
$folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
Run Code Online (Sandbox Code Playgroud)
}
当我运行上述 Powershell 脚本时,我收到此错误:
使用“7”参数调用“RegisterTaskDefinition”的异常:“指定的路径无效。(来自 HRESULT 的异常:0x800700A1)”在 C:\Users\me\Desktop\ST Testing\ImportSTs.ps1:22 char:5 + $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ ~ ~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException +fullyQualifiedErrorId : ComMethodTargetInvocation
提前致谢。
Register-ScheduledTask 支持使用 XML 定义任务:
Register-ScheduledTask `
-User $task_user `
-Password $task_pass `
-TaskName ([IO.Path]::GetFileNameWithoutExtension($task_path)) `
-TaskPath '\SubTasks' `
-Xml (Get-Content $task_path -Raw)
Run Code Online (Sandbox Code Playgroud)
请注意,您需要获取实际的 XML内容。该-Raw标志会阻止Get-Content返回 a String[],这也会让人Register-ScheduledTask不高兴。
另请注意,它Register-ScheduledTask有一个-TaskPath参数,允许您根据需要指定一个子文件夹来放置任务。
我不喜欢使用坟墓标记来延续行,所以我更喜欢 splatting 将事情分散到多行上:
$taskArgs = @{
User='usr';
Password='pwd';
TaskName=([IO.Path]::GetFileNameWithoutExtension($task_path));
TaskPath='\SubTasks';
Xml=(Get-Content $task_path -Raw)
}
Register-ScheduledTask @taskArgs
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16124 次 |
| 最近记录: |