Returning Failure if File does not exist












2















I am running the below script in SQL Server Agent.



All the subsequent steps in job are dependent upon this step. This is pretty simple Looking for a file and exits with failure if file is not found.



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

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


However when the agent job runs, it says the step failed because file not found and existing with code 0 - success.



What am I doing wrong here?










share|improve this question























  • I'm not sure what the issue is but if you don't need to store the result of test-path then you can just use if(!t(test-path -path $file)). You can also use if((test-path -path $file) -eq $false))

    – emanresu
    Nov 14 '18 at 21:15













  • Thank you for your response. The issue is, it exits with code=0 success. How do I fail this if file is not found?

    – Lucky
    Nov 14 '18 at 21:22






  • 1





    Don't escape backslashes in PowerShell string literals: has no special meaning (` is PowerShell's escape character), so it doesn't need escaping. That said, in file paths double backslashes are usually benign (treated the same as a single backslash). Is the file the job reports as not found really C:DataFileDrop.done? In your invocation scenario, is any exit code from your PowerShell script reflected in the job?

    – mklement0
    Nov 15 '18 at 3:16


















2















I am running the below script in SQL Server Agent.



All the subsequent steps in job are dependent upon this step. This is pretty simple Looking for a file and exits with failure if file is not found.



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

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


However when the agent job runs, it says the step failed because file not found and existing with code 0 - success.



What am I doing wrong here?










share|improve this question























  • I'm not sure what the issue is but if you don't need to store the result of test-path then you can just use if(!t(test-path -path $file)). You can also use if((test-path -path $file) -eq $false))

    – emanresu
    Nov 14 '18 at 21:15













  • Thank you for your response. The issue is, it exits with code=0 success. How do I fail this if file is not found?

    – Lucky
    Nov 14 '18 at 21:22






  • 1





    Don't escape backslashes in PowerShell string literals: has no special meaning (` is PowerShell's escape character), so it doesn't need escaping. That said, in file paths double backslashes are usually benign (treated the same as a single backslash). Is the file the job reports as not found really C:DataFileDrop.done? In your invocation scenario, is any exit code from your PowerShell script reflected in the job?

    – mklement0
    Nov 15 '18 at 3:16
















2












2








2








I am running the below script in SQL Server Agent.



All the subsequent steps in job are dependent upon this step. This is pretty simple Looking for a file and exits with failure if file is not found.



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

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


However when the agent job runs, it says the step failed because file not found and existing with code 0 - success.



What am I doing wrong here?










share|improve this question














I am running the below script in SQL Server Agent.



All the subsequent steps in job are dependent upon this step. This is pretty simple Looking for a file and exits with failure if file is not found.



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

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


However when the agent job runs, it says the step failed because file not found and existing with code 0 - success.



What am I doing wrong here?







powershell






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 20:59









LuckyLucky

597




597













  • I'm not sure what the issue is but if you don't need to store the result of test-path then you can just use if(!t(test-path -path $file)). You can also use if((test-path -path $file) -eq $false))

    – emanresu
    Nov 14 '18 at 21:15













  • Thank you for your response. The issue is, it exits with code=0 success. How do I fail this if file is not found?

    – Lucky
    Nov 14 '18 at 21:22






  • 1





    Don't escape backslashes in PowerShell string literals: has no special meaning (` is PowerShell's escape character), so it doesn't need escaping. That said, in file paths double backslashes are usually benign (treated the same as a single backslash). Is the file the job reports as not found really C:DataFileDrop.done? In your invocation scenario, is any exit code from your PowerShell script reflected in the job?

    – mklement0
    Nov 15 '18 at 3:16





















  • I'm not sure what the issue is but if you don't need to store the result of test-path then you can just use if(!t(test-path -path $file)). You can also use if((test-path -path $file) -eq $false))

    – emanresu
    Nov 14 '18 at 21:15













  • Thank you for your response. The issue is, it exits with code=0 success. How do I fail this if file is not found?

    – Lucky
    Nov 14 '18 at 21:22






  • 1





    Don't escape backslashes in PowerShell string literals: has no special meaning (` is PowerShell's escape character), so it doesn't need escaping. That said, in file paths double backslashes are usually benign (treated the same as a single backslash). Is the file the job reports as not found really C:DataFileDrop.done? In your invocation scenario, is any exit code from your PowerShell script reflected in the job?

    – mklement0
    Nov 15 '18 at 3:16



















I'm not sure what the issue is but if you don't need to store the result of test-path then you can just use if(!t(test-path -path $file)). You can also use if((test-path -path $file) -eq $false))

– emanresu
Nov 14 '18 at 21:15







I'm not sure what the issue is but if you don't need to store the result of test-path then you can just use if(!t(test-path -path $file)). You can also use if((test-path -path $file) -eq $false))

– emanresu
Nov 14 '18 at 21:15















Thank you for your response. The issue is, it exits with code=0 success. How do I fail this if file is not found?

– Lucky
Nov 14 '18 at 21:22





Thank you for your response. The issue is, it exits with code=0 success. How do I fail this if file is not found?

– Lucky
Nov 14 '18 at 21:22




1




1





Don't escape backslashes in PowerShell string literals: has no special meaning (` is PowerShell's escape character), so it doesn't need escaping. That said, in file paths double backslashes are usually benign (treated the same as a single backslash). Is the file the job reports as not found really C:DataFileDrop.done? In your invocation scenario, is any exit code from your PowerShell script reflected in the job?

– mklement0
Nov 15 '18 at 3:16







Don't escape backslashes in PowerShell string literals: has no special meaning (` is PowerShell's escape character), so it doesn't need escaping. That said, in file paths double backslashes are usually benign (treated the same as a single backslash). Is the file the job reports as not found really C:DataFileDrop.done? In your invocation scenario, is any exit code from your PowerShell script reflected in the job?

– mklement0
Nov 15 '18 at 3:16














3 Answers
3






active

oldest

votes


















1














I don't think the return value / error code of the job has anything to do with whatever value the script returns.



If you want to fail with an error message, try this:



# make sure to stop on errors
$ErrorActionPreference = 'Stop'
$path = 'C:DataFileDrop.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...


This should fail the job entirely and show the error message in the job's history.






share|improve this answer


























  • If the OP doesn't actually care about the setting the exit code and just wants to ensure that the job fails in this condition then I think this is the correct answer.

    – emanresu
    Nov 16 '18 at 17:09



















0














Maybe this is what you're looking for:



if(!(Test-Path "C:DataFileDrop.done")){
return 1
}
else {
return 0
}





share|improve this answer































    0














    This is not going to be a great answer because I have not found the documentation that explains this but the use of Exit followed by a number seems to not have any effect on the exit code.



    The following example works, with the general idea taken from a blog.
    First create a test script like the following:



    $host.SetShouldExit(12345)
    exit


    Next call this script from the Powershell command line as in the following example:



    $command = "C:YourTestScriptPathAndName.ps1"
    Powershell -NonInteractive -NoProfile -Command $command


    The script will run and exit, and we can then check the exit code from the Powershell prompt by writing out the contents of $LASTEXISTCODE



    $LASTEXITCODE


    In this case $LASTEXISTCODE would contain 12345.



    In the case of using this with Test-Path it would look like this:



    #using a path that does not exist
    if(Test-Path -Path 'C:nope'){
    $host.SetShouldExit(1234)
    }
    else{
    $host.SetShouldExit(2222)
    }


    This sets the exit code to 2222 when invoked from the command line, but when I invoke that test script from another script instead of from the command line the $LASTEXITCODE variable is set to 0 still.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308618%2freturning-failure-if-file-does-not-exist%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      I don't think the return value / error code of the job has anything to do with whatever value the script returns.



      If you want to fail with an error message, try this:



      # make sure to stop on errors
      $ErrorActionPreference = 'Stop'
      $path = 'C:DataFileDrop.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...


      This should fail the job entirely and show the error message in the job's history.






      share|improve this answer


























      • If the OP doesn't actually care about the setting the exit code and just wants to ensure that the job fails in this condition then I think this is the correct answer.

        – emanresu
        Nov 16 '18 at 17:09
















      1














      I don't think the return value / error code of the job has anything to do with whatever value the script returns.



      If you want to fail with an error message, try this:



      # make sure to stop on errors
      $ErrorActionPreference = 'Stop'
      $path = 'C:DataFileDrop.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...


      This should fail the job entirely and show the error message in the job's history.






      share|improve this answer


























      • If the OP doesn't actually care about the setting the exit code and just wants to ensure that the job fails in this condition then I think this is the correct answer.

        – emanresu
        Nov 16 '18 at 17:09














      1












      1








      1







      I don't think the return value / error code of the job has anything to do with whatever value the script returns.



      If you want to fail with an error message, try this:



      # make sure to stop on errors
      $ErrorActionPreference = 'Stop'
      $path = 'C:DataFileDrop.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...


      This should fail the job entirely and show the error message in the job's history.






      share|improve this answer















      I don't think the return value / error code of the job has anything to do with whatever value the script returns.



      If you want to fail with an error message, try this:



      # make sure to stop on errors
      $ErrorActionPreference = 'Stop'
      $path = 'C:DataFileDrop.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...


      This should fail the job entirely and show the error message in the job's history.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 15 '18 at 12:36

























      answered Nov 15 '18 at 10:22









      marszemarsze

      5,16832041




      5,16832041













      • If the OP doesn't actually care about the setting the exit code and just wants to ensure that the job fails in this condition then I think this is the correct answer.

        – emanresu
        Nov 16 '18 at 17:09



















      • If the OP doesn't actually care about the setting the exit code and just wants to ensure that the job fails in this condition then I think this is the correct answer.

        – emanresu
        Nov 16 '18 at 17:09

















      If the OP doesn't actually care about the setting the exit code and just wants to ensure that the job fails in this condition then I think this is the correct answer.

      – emanresu
      Nov 16 '18 at 17:09





      If the OP doesn't actually care about the setting the exit code and just wants to ensure that the job fails in this condition then I think this is the correct answer.

      – emanresu
      Nov 16 '18 at 17:09













      0














      Maybe this is what you're looking for:



      if(!(Test-Path "C:DataFileDrop.done")){
      return 1
      }
      else {
      return 0
      }





      share|improve this answer




























        0














        Maybe this is what you're looking for:



        if(!(Test-Path "C:DataFileDrop.done")){
        return 1
        }
        else {
        return 0
        }





        share|improve this answer


























          0












          0








          0







          Maybe this is what you're looking for:



          if(!(Test-Path "C:DataFileDrop.done")){
          return 1
          }
          else {
          return 0
          }





          share|improve this answer













          Maybe this is what you're looking for:



          if(!(Test-Path "C:DataFileDrop.done")){
          return 1
          }
          else {
          return 0
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 9:27









          TobyUTobyU

          2,3681921




          2,3681921























              0














              This is not going to be a great answer because I have not found the documentation that explains this but the use of Exit followed by a number seems to not have any effect on the exit code.



              The following example works, with the general idea taken from a blog.
              First create a test script like the following:



              $host.SetShouldExit(12345)
              exit


              Next call this script from the Powershell command line as in the following example:



              $command = "C:YourTestScriptPathAndName.ps1"
              Powershell -NonInteractive -NoProfile -Command $command


              The script will run and exit, and we can then check the exit code from the Powershell prompt by writing out the contents of $LASTEXISTCODE



              $LASTEXITCODE


              In this case $LASTEXISTCODE would contain 12345.



              In the case of using this with Test-Path it would look like this:



              #using a path that does not exist
              if(Test-Path -Path 'C:nope'){
              $host.SetShouldExit(1234)
              }
              else{
              $host.SetShouldExit(2222)
              }


              This sets the exit code to 2222 when invoked from the command line, but when I invoke that test script from another script instead of from the command line the $LASTEXITCODE variable is set to 0 still.






              share|improve this answer




























                0














                This is not going to be a great answer because I have not found the documentation that explains this but the use of Exit followed by a number seems to not have any effect on the exit code.



                The following example works, with the general idea taken from a blog.
                First create a test script like the following:



                $host.SetShouldExit(12345)
                exit


                Next call this script from the Powershell command line as in the following example:



                $command = "C:YourTestScriptPathAndName.ps1"
                Powershell -NonInteractive -NoProfile -Command $command


                The script will run and exit, and we can then check the exit code from the Powershell prompt by writing out the contents of $LASTEXISTCODE



                $LASTEXITCODE


                In this case $LASTEXISTCODE would contain 12345.



                In the case of using this with Test-Path it would look like this:



                #using a path that does not exist
                if(Test-Path -Path 'C:nope'){
                $host.SetShouldExit(1234)
                }
                else{
                $host.SetShouldExit(2222)
                }


                This sets the exit code to 2222 when invoked from the command line, but when I invoke that test script from another script instead of from the command line the $LASTEXITCODE variable is set to 0 still.






                share|improve this answer


























                  0












                  0








                  0







                  This is not going to be a great answer because I have not found the documentation that explains this but the use of Exit followed by a number seems to not have any effect on the exit code.



                  The following example works, with the general idea taken from a blog.
                  First create a test script like the following:



                  $host.SetShouldExit(12345)
                  exit


                  Next call this script from the Powershell command line as in the following example:



                  $command = "C:YourTestScriptPathAndName.ps1"
                  Powershell -NonInteractive -NoProfile -Command $command


                  The script will run and exit, and we can then check the exit code from the Powershell prompt by writing out the contents of $LASTEXISTCODE



                  $LASTEXITCODE


                  In this case $LASTEXISTCODE would contain 12345.



                  In the case of using this with Test-Path it would look like this:



                  #using a path that does not exist
                  if(Test-Path -Path 'C:nope'){
                  $host.SetShouldExit(1234)
                  }
                  else{
                  $host.SetShouldExit(2222)
                  }


                  This sets the exit code to 2222 when invoked from the command line, but when I invoke that test script from another script instead of from the command line the $LASTEXITCODE variable is set to 0 still.






                  share|improve this answer













                  This is not going to be a great answer because I have not found the documentation that explains this but the use of Exit followed by a number seems to not have any effect on the exit code.



                  The following example works, with the general idea taken from a blog.
                  First create a test script like the following:



                  $host.SetShouldExit(12345)
                  exit


                  Next call this script from the Powershell command line as in the following example:



                  $command = "C:YourTestScriptPathAndName.ps1"
                  Powershell -NonInteractive -NoProfile -Command $command


                  The script will run and exit, and we can then check the exit code from the Powershell prompt by writing out the contents of $LASTEXISTCODE



                  $LASTEXITCODE


                  In this case $LASTEXISTCODE would contain 12345.



                  In the case of using this with Test-Path it would look like this:



                  #using a path that does not exist
                  if(Test-Path -Path 'C:nope'){
                  $host.SetShouldExit(1234)
                  }
                  else{
                  $host.SetShouldExit(2222)
                  }


                  This sets the exit code to 2222 when invoked from the command line, but when I invoke that test script from another script instead of from the command line the $LASTEXITCODE variable is set to 0 still.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 16 '18 at 16:16









                  emanresuemanresu

                  40626




                  40626






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308618%2freturning-failure-if-file-does-not-exist%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Bressuire

                      Vorschmack

                      Quarantine