首页 > 解决方案 > 使用 Exit 与 Break 完全完成脚本运行

问题描述

在周六和周日,可能不会创建此脚本扫描其模式匹配的文件 - 如果文件存在,我应该在哪里进行测试 - 在 While 循环之前或在其中?当文件存在时,它运行得很好——但在周六运行时——它没有退出,周一早上仍在运行。

If(!( Test-Path -Path $Directory\$Source)) {exit or break?}

这是当前代码---


$job = Start-Job {
    # Note: $file should be the absolute path of your file
    Get-Content $File -Raw | Select-string -Pattern "Idle" -Quiet
}

while($true)
{
    # if the job has completed
    if($job.State -eq 'Completed')
    {
        $result = $job|Receive-Job

        # if result is True
        if($result)
        {
            $elapsedTime.Stop()
            $duration = $elapsedTime.Elapsed.ToString("hh\:mm\:ss")
            
            # .... send email logic here
            # for success result

            break #=> This is important, don't remove it
        }

        # we don't need a else here,
        # if we are here is because $result is false
        
        $elapsedTime.Stop()
        $duration = $elapsedTime.Elapsed.ToString("hh\:mm\:ss")

        # .... send email logic here
        # for unsuccessful result
        
        break #=> This is important, don't remove it
    }

    # if this is running for more than
    # 60 minutes break the loop
    if($elapsedTime.Elapsed.Minutes -ge 60)
    {
        $elapsedTime.Stop()
        $duration = $elapsedTime.Elapsed.ToString("hh\:mm\:ss")
        
        # .... send email logic here
        # for script running longer 
        # than 60 minutes

        break #=> This is important, don't remove it
    }
    
    Start-Sleep -Milliseconds 500
}

Get-Job|Remove-Job ```

标签: powershell

解决方案


  • 退出整个脚本(甚至从脚本中的函数退出),请使用exit.

    • 如果您在脚本exit 之外使用:

      • 一个交互会话作为一个整体被终止。
      • exit作业的脚本块内(以Start-Jobor开头Start-ThreadJob)终止该作业(尽管其先前的输出,如果有的话,仍然可以用 检索Receive-Job)。
    • 要仅退出一个函数,请使用return.

  • break并且continue应该只用于跳出循环foreach/ for、、、whiledoswitch语句

    • 陷阱:如果您使用breakcontinue 使用封闭循环或switch语句,PowerShell 会查找此类语句的调用堆栈并退出它找到的第一个此类语句;如果没有,则终止当前调用堆栈。也就是说,至少封闭脚本终止。
      也就是说,break可能会在某些情况下意外地表现得像exit(无法指定退出代码),但您永远不应该依赖它。

有关更多信息,请参阅此答案的底部。


推荐阅读