在Windows 2008R2服务器上,我必须使用本机schtasks来安排任务。我创建了以下脚本,首先删除任何ID为Watson的旧任务,然后安排它。唯一的问题是化妆品。 Schtasks / DELETE将给出错误:
ERROR: The system cannot find the path specified
如果任务原本不在那里。不是一个非常友好的消息。我想做一个
schtasks /QUERY /TN $name
找出它当前是否存在,然后才删除它。但我的powershell技能并不符合它。我尝试了一个TRY块,但它似乎不适用于本机应用程序)
有什么建议吗?
start-transcript -Path install.log -Append
Write-Host "schedule.ps1 Script`r`n"
$reg = Get-Item -Path "hklm:\SOFTWARE\Draper Laboratory\EGPL\GeoLibrarian"
$path = $reg.GetValue('VHDPath').ToString()
$name = "Watson"
$bin = "powershell.exe"
$trigger = "ONCE"
$ts = New-TimeSpan -Minutes 1
$time = (get-date) + $ts
$when = "{0:HH\:mm}" -f $time
$policy ="-executionpolicy Unrestricted"
$profile = "-noprofile"
$file = "$path\setup\boot-watson.ps1"
$sixtyfour = [Environment]::Is64BitProcess
Write-Host "64-Bit Powershell: "$sixtyfour
Write-Host "PowerShell Version: "$PSVersionTable.PSVersion
Write-Host "Deleting old watson task"
schtasks /DELETE /TN $name /F 2>&1 | %{ "$_" }
Write-Host "If watson was not scheduled, ignore ERROR: The system cannot find the path specified"
Write-Host "Adding new watson start-up task"
#schtasks /CREATE /TN $name /TR "$bin $policy $profile -file $file" /SC $trigger /ST $when /RU SYSTEM /RL HIGHEST 2>&1 | %{ "$_" } | Out-Host
schtasks /CREATE /TN $name /TR "$bin $policy $profile -file $file" /SC ONSTART /RU SYSTEM /RL HIGHEST 2>&1 | %{ "$_" } | Out-Host
更新
我尝试执行/查询,但如果没有任务,那么它本身会转储大量错误文本。
schtasks : ERROR: The system cannot find the file specified.
At G:\wwwroot\setup\uninstall.ps1:11 char:1
+ schtasks /QUERY /TN $name | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ERROR: The syst...file specified.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
答案 0 :(得分:1)
您可以使用指示最后退出代码的两个自动变量之一:$LASTEXITCODE
和$?
如果schtasks /query
成功,$LASTEXITCODE
将0
而$?
将成为$true
另一方面,如果schtasks /query
调用失败,$LASTEXITCODE
将包含非0退出代码,$?
将评估为$false
:
schtasks /QUERY /TN $name > $null 2>&1
if($?){
schtasks /DELETE /TN $name /F
}
或者,使用$LASTEXITCODE
:
schtasks /QUERY /TN $name > $null 2>&1
if($LASTEXITCODE -eq 0){
schtasks /DELETE /TN $name /F
}
使用output redirection与$null
来压制schtasks
的错误/输出