首页 > 解决方案 > 如果文件不存在则返回失败

问题描述

我在 SQL Server 代理中运行以下脚本。

作业中的所有后续步骤都取决于此步骤。这是非常简单的查找文件并在未找到文件时退出并失败。

  $file = "C:\\Data\\FileDrop\\.done"
  $CheckFile = Test-Path -Path $file

  if (!($CheckFile))  {exit 1 } 

但是,当代理作业运行时,它说该步骤失败,因为找不到文件并且存在代码 0 - 成功。

我在这里做错了什么?

标签: powershell

解决方案


我不认为作业的返回值/错误代码与脚本返回的任何值有任何关系。

如果您想失败并显示错误消息,请尝试以下操作:

# 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...

这应该会使作业完全失败,并在作业历史记录中显示错误消息。


推荐阅读