我正在SQL Server代理中运行以下脚本。
作业中的所有后续步骤均取决于此步骤。这非常简单,可以查找文件,如果找不到文件,则退出并失败。
$file = "C:\\Data\\FileDrop\\.done"
$CheckFile = Test-Path -Path $file
if (!($CheckFile)) {exit 1 }
但是,当代理程序作业运行时,它说该步骤失败了,因为未找到文件并且代码为0-成功。
我在这里做什么错了?
答案 0 :(得分:1)
我认为作业的返回值/错误代码与脚本返回的值无关。
如果您想失败并显示错误消息,请尝试以下操作:
# make sure to stop on errors
$ErrorActionPreference = 'Stop'
$path = 'C:\Data\FileDrop\.done'
# check for file explicitly (in case a directory with that name exists)
if(![System.IO.File]::Exists($path)) {
# throwing an exception will abort the job
throw (New-Object System.IO.FileNotFoundException("File not found: $path", $path))
}
# anything after this will not be executed on error...
这应该会使作业完全失败,并在作业的历史记录中显示错误消息。
答案 1 :(得分:0)
也许这就是您想要的:
if(!(测试路径“ C:\ Data \ FileDrop \ .done”)){
返回1
}
其他{
返回0
}
答案 2 :(得分:0)
这不会是一个很好的答案,因为我还没有找到解释该问题的文档,但是使用Exit加上数字似乎对退出代码没有任何影响。
下面的示例有效,其基本思想来自blog。 首先创建如下测试脚本:
$host.SetShouldExit(12345)
exit
接下来,如以下示例所示,从Powershell命令行调用此脚本:
$command = "C:\YourTestScriptPathAndName.ps1"
Powershell -NonInteractive -NoProfile -Command $command
脚本将运行并退出,然后我们可以通过写出$ LASTEXISTCODE的内容来从Powershell提示符中检查退出代码
$LASTEXITCODE
在这种情况下,$ LASTEXISTCODE将包含12345。
在将它与Test-Path一起使用时,它看起来像这样:
#using a path that does not exist
if(Test-Path -Path 'C:\nope'){
$host.SetShouldExit(1234)
}
else{
$host.SetShouldExit(2222)
}
这在从命令行调用时将退出代码设置为2222,但是当我从另一个脚本而不是从命令行调用该测试脚本时,$ LASTEXITCODE变量仍设置为0。