Powershell 返回错误结果

编程入门 行业动态 更新时间:2024-10-12 05:55:45
本文介绍了Powershell 返回错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在 Powershell 中遇到了这个奇怪的问题(不是在其他语言中).任何人都可以向我解释为什么会发生这种情况吗?

我试图返回一个指定的数字(数字 8),但该函数不断向我抛出所有内容.这是错误还是设计?

函数 GetNum() {返回 10}函数主(){$Number10 = GetNum$number10 #1 为什么这里没有输出???????我不想使用写主机$result = 8 # 我只想要这个数字暂停返回 $result}做 {$again = 主要Write-Host "RESULT IS "$again # 奇怪的结果,我只想要数字 8} while ($again -eq 10) # 由于结果错误,一直循环

解决方案

这是错误还是有意为之?

按设计.在 PowerShell 中,cmdlet 可以返回对象流,就像在 C# 中使用 yield return 返回 IEnumerable 集合一样.

return 关键字不需要返回输出值,它只是退出(或从返回)当前范围.

来自 Get-Help about_Return(强调):

Return 关键字退出函数、脚本或脚本块.有可能用于在特定点退出作用域、返回值或指示已达到范围的末尾.熟悉 C 或 C# 等语言的用户可能希望使用Return 关键字使离开范围的逻辑明确.在 Windows PowerShell 中,每个语句的结果返回为输出,即使没有包含 Return 关键字的语句.C 或 C# 等语言仅返回指定的一个或多个值通过 Return 关键字.

I came across this weird issue in Powershell (not in other languages). Could anyone please explain to me why this happened?

I tried to return a specified number (number 8), but the function keeps throwing everything at me. Is that a bug or by design?

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

解决方案

Is that a bug or by design?

By design. In PowerShell, cmdlets can return a stream of objects, much like using yield return in C# to return an IEnumerable collection.

The return keyword is not required for output values to be returned, it simply exits (or returns from) the current scope.

From Get-Help about_Return (emphasis added):

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.

更多推荐

Powershell 返回错误结果

本文发布于:2023-11-22 01:13:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615396.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   Powershell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!