使用 powershell 和 schtasks 尝试捕获失败 [英] try-catch-fail with powershell and schtasks

查看:37
本文介绍了使用 powershell 和 schtasks 尝试捕获失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 powershell 的新手,但我试图在我正在编写的 ps 中输出一些简单的日志记录来创建计划任务.我的代码如下.当您遇到 schtasks 错误时,它似乎不会引发异常.另一个 SO 问题在 fileIO 操作中提到了这一点,并建议执行-ea stop",但这不适用于 schtasks.

I'm new to powershell, but I'm trying to output some simple logging in a ps I'm writing to create scheduled tasks. My code is below. It seems that it doesn't throw an exception when you get an error with schtasks. Another SO question mentioned this with fileIO actions and suggested doing "-ea stop" but that doesn't work with schtasks.

#create log file
$log = "\\servername\!incoming\Deploy\log.txt"
Clear-Content $log

#get input file list
$txtServerList = Gc "\\servername\!incoming\Deploy\serverlist.txt"
#loop through each server
ForEach($strServername In $txtServerList)
{
    try 
    {
        #install task from XML template
        schtasks /create /s $strServername /tn InventoryServer /XML "\\servername\!incoming\Deploy\TaskTemplate.xml"
        #run the task immediately
        schtasks /run /s $strServername /tn InventoryServer
    }
    catch [exception]
    {
       Add-Content -path $log -value $strServername
       #Add-Content -path $log -value $_.Exception
       #Add-Content -path $log -value $_.Exception.Message
       #Add-Content -path $log -value ""
    }
}

我确认 'Add-Content -path "\servername!incoming\Deploy\log.txt" -value "test"' 有效,所以就像我说的那样,我很确定它只是没有抛出异常.

I verified that 'Add-Content -path "\servername!incoming\Deploy\log.txt" -value "test"'works, so like I said I'm fairly sure it's just not throwing an exception.

推荐答案

为了使 Try/Catch 工作,PowerShell 需要终止异常.在 Try 块中运行 cmdlet 时,您可以通过使用 -erroraction Stop(或使用 -ea 别名)来实现这一点.正如您已经意识到 SCHTASKS.EXE 无法做到这一点.如果没有终止异常,Catch 块中的代码将永远不会运行.

In order for a Try/Catch to work, PowerShell needs a terminating exception. When running a cmdlet in a Try block you can make that happen by using -erroraction Stop (or use the -ea alias). As you already realize SCHTASKS.EXE can't do this. Without a terminating exception, the code in the Catch block will never run.

你要做的就是走出盒子,可以这么说,独立检查 Schtasks 是否失败.如果是这样,您可以在 Try 块中使用 Write-Error.

What you have to do is step out side the box, so to speak, and independently check if Schtasks failed. If so, they you can use Write-Error in your Try block.

您可以尝试的一件事是使用 Start-Process 并查看退出代码.0 以外的任何值都应该是错误.

One thing you might try is using Start-Process and look at the exit code. Anything other than 0 should be an error.

Try {
get-date
$p=Start-Process schtasks.exe -ArgumentList "/Create foo" -wait -passthru
if ($p.exitcode -ne 0) {
    write-error "I failed with error $($p.exitcode)"
}
}

Catch {
"oops"
$_.Exception
}

这篇关于使用 powershell 和 schtasks 尝试捕获失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆