PowerShell中的“退出”到底是什么?


73

您可以通过键入退出PowerShell exit。到现在为止还挺好。但这到底是什么?

PS Home:\> gcm exit
Get-Command : The term 'exit' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:4
+ gcm <<<<  exit
    + CategoryInfo          : ObjectNotFound: (exit:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

因此,它既不是cmdlet,函数,脚本或程序。剩下的问题它到底是什么

不幸的是,这也意味着无法创建别名exit

PS Home:\> New-Alias ^D exit
PS Home:\> ^D
Cannot resolve alias '♦' because it refers to term 'exit', which is not recognized as a cmdlet, function, operable prog
ram, or script file. Verify the term and try again.
At line:1 char:2
+ ♦ <<<<
    + CategoryInfo          : ObjectNotFound: (♦:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : AliasNotResolvedException

还有没有这种命令的命令吗?

ETA:仅供参考:我知道我可以将其包装为一个函数。我的个人资料已上线

# exit with Ctrl+D
iex "function $([char]4) { exit }"

在他们之中。我的问题只是想知道此命令的确切含义。

Answers:


109

这是一个保留关键字(例如return,filter,function,break)。

参考

此外,根据布鲁斯·佩耶特(Bruce Payette)的《Powershell在行动》第7.6.4节:

但是,当您希望脚本从该脚本定义的函数中退出时会发生什么?...为了简化此操作,Powershell提供了exit关键字

当然,正如其他人指出的那样,通过将退出包装在函数中来完成您想要的事情并不困难:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

4
根据Get-Help Exit-PSSession 您还可以使用Exit关键字结束交互式会话。效果与使用Exit-PSSession相同。因此它也说Exit是一个关键字。但是,似乎引号不能被认为是暗示,Exit并且Exit-PSSession在所有情况下都是等效的。exit关键字可以与可以转换为的参数一起使用[int],在这种情况下,该数字将是退出代码。例如Exit 42
杰普·斯蒂格·尼尔森

我必须说,这个答案是完全错误的。我在$ profile中放了一个函数,在那个函数中,我在一定条件下放了一个“退出”按钮,它没有退出功能,而是退出了整个控制台。我已经浪费了好几个小时来寻找可以在不终止控制台会话的情况下保留某个功能的东西,我为此感到困惑。以上肯定是错误的。
YorSubs

那么,可能是因为$ profile被点源到当前会话中了?在这种情况下,exit那里的一个函数内部完全无法执行上面的Bruce Payette所描述的。如果真是这样,那么那部分答案是错误的,因为基于点源的脚本仍然是控制台会话调用的脚本,所以它仍然是脚本(!),但是如果没有这种方法,我们又如何才能退出函数呢?如果脚本是点源的,是否退出控制台会话?
YorSubs

@YorSubs,如果您阅读链接的参考,它会指出exit“导致PowerShell退出脚本或PowerShell实例。” 退出实例是预期的行为。如果要退出功能,只需使用即可return。来自相同的参考:“使PowerShell离开当前范围,例如脚本或函数,并将可选表达式写入输出。” 这return对于返回值(包括空白)在PowerShell中的功能并没有成为习惯是奇怪,从其他编程语言的到来,但是,这是除了点。
PartyLich
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.