powershell - 使用 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 ```
解决方案
要退出整个脚本(甚至从脚本中的函数退出),请使用
exit
.如果您在脚本
exit
之外使用:- 一个交互会话作为一个整体被终止。
exit
在作业的脚本块内(以Start-Job
or开头Start-ThreadJob
)终止该作业(尽管其先前的输出,如果有的话,仍然可以用 检索Receive-Job
)。
要仅退出一个函数,请使用
return
.
break
并且continue
应该只用于跳出循环(foreach
/for
、、、while
)do
和switch
语句。- 陷阱:如果您使用
break
或continue
不使用封闭循环或switch
语句,PowerShell 会查找此类语句的调用堆栈并退出它找到的第一个此类语句;如果没有,则终止当前调用堆栈。也就是说,至少封闭脚本终止。
也就是说,break
可能会在某些情况下意外地表现得像exit
(无法指定退出代码),但您永远不应该依赖它。
- 陷阱:如果您使用
有关更多信息,请参阅此答案的底部。
推荐阅读
- python - 如何在python中获取低于json格式的键的特定值
- git - 将推送内容的部分预推送挂钩更改为 git 服务器
- php - Laravel:将数据从购物车传递到结帐页面
- java - JMH Timeout 不会中断
- c - w25q128fw 外部 spi flash 没有响应从 stm32 发送的命令
- mysql - SQL 过程参数
- scikit-learn - precompute_distances 在 sklearn kmeans 方法中做了什么?
- python - 每 N 行后重复一次 pandas 方法
- android - 选项菜单项中的自定义布局显示为空布局
- vba - Outlook将附件保存到文件不起作用