当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 退出脚本 - 如何终止脚本

作者:精品下载站 日期:2024-12-14 16:40:19 浏览:12 分类:玩电脑

PowerShell 退出脚本 - 如何终止脚本


PowerShell Exit 函数终止脚本。在 PowerShell 中使用 Exit 关键字可以终止范围内的控制台或脚本。它停止 PowerShell 脚本。

使用 PowerShell 中的 Exit cmdlet,您可以退出远程 PowerShell 会话。

在本文中,我们将讨论如何在 PowerShell 中使用 exit 关键字退出脚本。

我们将通过示例讨论脚本中用作退出函数的其他 cmdlet,例如 Exit、Break、Return 和 Exit-PSSession。

让我们来练习!

使用 PowerShell Exit 关键字

PowerShell中的Exit关键字可以终止脚本、控制台会话。

如果您打开 PowerShell 控制台并输入 exit,它将立即关闭。

PS C:\> Exit

在脚本中使用 Exit 关键字只会终止脚本,而不会终止运行脚本的控制台会话。

将脚本保存在文件中为 FuncTest.ps1

Function ExitFunctionTest{
Write-Output "Inside function..."
Exit
}

下一步是从控制台调用脚本。

它将在控制台上显示“Inside Function…”消息并停止 PowerShell 脚本。

控制台将保持打开状态。

[玩转系统] PowerShell 退出脚本 - 如何终止脚本

酷提示: PowerShell 在 Windows 中回显等效命令!

使用 Break 关键字

Break 关键字主要用在 PowerShell 中的循环中,例如(For、while、foreach、do-while 等)。

它退出当前循环。

for($count =1; $count -lt 5;$count++) {

	if($count -eq 3)
		{ break}
   Write-Output "Current Counter Value:" $count
}

在上面的示例中,我们使用 for 循环来演示使用break关键字的PowerShell退出功能。

$count 变量值在每次迭代时增加 +1。

在for循环中,它检查条件,如果$count的值等于3,则执行break语句。

这将终止 for 循环并退出 for 循环。

它停止 PowerShell 脚本并开始执行 for 循环后的下一条语句。

上述使用break的PowerShell退出脚本的输出是:

[玩转系统] PowerShell 退出脚本 - 如何终止脚本

酷提示:如何将多个参数传递给 PowerShell 中的函数!

使用 Return 关键字

在 PowerShell 脚本中使用 Return 关键字可返回到调用它的位置。

Return 关键字不会终止脚本或会话。

让我们通过一个例子来理解 return 关键字。

Function CheckStatus ($bitStatus){
	If($bitStatus = 2) 
		{
			return $true
		} 
	else
		{
			return $false
		}

	Write-Output "Bit Status check function called"  		
}

Write-Output "Call to Bit Status check function"
CheckStatus(2) # Invoke the function
Write-Output "CheckStatus function called"

在上面的 PowerShell 退出脚本示例中,

如果 bitStatus 等于 2,函数 CheckBitStatus 返回 true。

您可以返回任何类型的值。

酷提示:在 PowerShell 中使用 Active Directory UserAccountControl 标志!

上述函数的输出为:

Call to Bit Status check function
True
CheckStatus function called

评估条件后,它从函数退出,返回到调用它的位置,并继续执行进一步的语句。

酷提示:如何在 PowerShell 中连接字符串!

结论

PowerShell Exit 关键字可以终止脚本、循环、控制台。函数中的 PowerShell exit 会停止 PowerShell 脚本。

在脚本或循环中使用break关键字,它将退出该脚本或循环的当前范围。

在脚本中使用 return 关键字,它将返回到调用它的位置。

酷提示:如何在 PowerShell 中向字符串添加换行符!

使用 return 关键字,您可以返回任何类型的值。

每个关键字都有自己的用例。

酷提示:如何使用 PowerShell NoExit 保持 PS 控制台窗口打开!

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯