简体   繁体   English

Powershell 脚本来查找/运行计划任务或创建

[英]Powershell Script To Find/Run Scheduled Task or Create

I am trying to figure out how to write a PowerShell script to find and run a scheduled task, or if it is not there then to create it.我试图弄清楚如何编写 PowerShell 脚本来查找和运行计划任务,或者如果它不存在则创建它。 Here is what I have built so far.这是我到目前为止所构建的。 The else statement works but the first task does not. else 语句有效,但第一个任务无效。

$taskName = "crebackup"
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName}

if($taskExists) {
     Start-ScheduledTask -TaskName "crebackup"}

else {
$action = New-ScheduledTaskAction -Execute “C:\POSNation\SQLBackup\sqlbackup.exe”
$Trigger = New-ScheduledTaskTrigger -Daily -At 3am
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName 'crebackup' -InputObject $Task -User 'usernamehere' -Password 'passwordhere'}

In this case the sqlbackup.exe task needed the working directory to start in. This is displayed as "Start in (optional)" when you look at the task using Task Scheduler.在这种情况下,sqlbackup.exe 任务需要工作目录才能启动。当您使用任务计划程序查看任务时,这将显示为“启动(可选)”。 To add that, use this for the $action variable:要添加它,请将其用于$action变量:

$action = New-ScheduledTaskAction -WorkingDirectory "C:\POSNation\SQLBackup" -Execute "C:\POSNation\SQLBackup\sqlbackup.exe"

Also, make sure scripts don't have any smart quotes in them( , ).另外,请确保脚本中没有任何智能引号( , )。 Smart quotes are often automatically generated by word processors and some websites.智能引号通常由文字处理器和某些网站自动生成。 I replaced the smart quotes in the example above.我替换了上面示例中的智能引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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