[英]Powershell returns wrong result
我在Powershell(不是其他语言)中遇到了这个奇怪的问题。 有人可以向我解释为什么会这样吗?
我试图返回一个指定的数字(数字8),但是该函数不断抛出所有错误。 这是错误还是设计使然?
Function GetNum() {
Return 10
}
Function Main() {
$Number10 = GetNum
$number10 #1 WHY NO OUTPUT HERE ??????? I don't want to use write host
$result = 8 # I WANT THIS NUMBER ONLY
PAUSE
return $result
}
do {
$again = Main
Write-Host "RESULT IS "$again # Weird Result, I only want Number 8
} While ($again -eq 10) # As the result is wrong, it loops forever
这是错误还是设计使然?
通过设计。 在PowerShell中,cmdlet可以返回对象流,就像在C#中使用yield return
返回IEnumerable
集合一样。
要返回输出值,不需要return
关键字,它只是退出当前作用域(或从中返回 )。
从Get-Help about_Return
(添加了重点):
The Return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached. Users who are familiar with languages like C or C# might want to use the Return keyword to make the logic of leaving a scope explicit. In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the Return keyword.
Mathias像往常一样出现。
我想在您的代码中解决此评论:
$number10 #1 WHY NO OUTPUT HERE ??????? I don't want to use write host
您为什么不想使用Write-Host
? 是否是因为您可能遇到过PowerShell创作者的这篇非常受欢迎的帖子,标题是“ Write-Host
认为有害” ?
如果是这样,我鼓励您阅读tby所写的标题为Write-Host
真的有害吗?
有了这些信息,很显然,正如Mathias所说,您正在将对象返回到管道中,但是您还应该掌握选择替代方案所需的信息,无论是Write-Verbose
, Write-Debug
还是Write-Host
。
如果我对此持怀疑态度,可以使用Write-Verbose
,稍微修改一下函数定义以支持它:
function Main {
[CmdletBinding()]
param()
$Number10 = GetNum
Write-Verbose -Message $number10
$result = 8 # I WANT THIS NUMBER ONLY
PAUSE
$result
}
当您仅通过调用$again = Main
调用它时,屏幕上将看不到任何内容,并且$again
的值为8
。 但是,如果您这样称呼:
$again = Main -Verbose
那么$again
的值仍然为8
,但是在屏幕上您会看到:
VERBOSE: 10
可能使用不同颜色的文本。
给出的结果不仅是显示值的方法,而且是调用方控制他们是否看到该值而不改变该函数的返回值的一种方法 。
为了进一步说明文章中的某些要点,请考虑不一定需要使用-Verbose
调用函数来实现这一点。
例如,假设您将整个脚本存储在名为FeelingNum.ps1
的文件中。
如果除了我上面所做的更改之外,还将以下内容添加到文件的最顶部:
[CmdletBinding()]
param()
然后,您仍然以“通常”的方式$again = Main
调用$again = Main
,可以通过-Verbose
调用脚本来获得详细的输出:
powershell.exe -File FeelingNum.ps1 -Verbose
发生的事情是,使用-Verbose
参数设置了一个名为$VerbosePreference
的变量,并且该变量将在调用堆栈的每个函数上继承(除非被覆盖)。 您也可以手动设置$VerbosePreference
。
因此,无论您是作者还是使用您代码的任何人,使用这些内置功能都将获得很大的灵活性,即使使用它的唯一人也是一件好事 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.