powershell - Powershell 中的显式返回

标签 powershell pure-function

我可以用javascript编写以下代码:

function sum(num1, num2) {
  return num1 + num2;
}

然后得到一个值

var someNum = sum(2,5);

我想在 Powershell 中做同样的事情,但我阅读了 following guide:

PowerShell also knows the return keyword; however, it follows a different logic. In general, the purpose of return is to end the execution of a code section and to give the control back to the parent block.

If you add a parameter to the return statement, the value will indeed be returned to the calling subroutine. However, this also applies for all other statements with an output. This means that any output produced in the function will be stored in the variable together with the return parameter.

我想这样做是为了拥有纯函数。但是,它似乎在做

var someNum = sum(2,5);

完全是多余的,当我可以调用上面的函数时,在其中定义someNum,它将在全局范围内可用。

我是否遗漏了什么,或者是否可以在 Powershell 中编写不返回函数内部所有内容的纯函数?


有点切题,但这是我的实际代码:

function GetPreviousKeyMD5Hashes() {
    $query = "SELECT Name, MD5, executed FROM [AMagicDb].[dbo].cr_Scripts";

    $command = New-Object System.Data.SQLClient.SQLCommand;
    $command.Connection = $connection;
    $command.CommandText = $query;

    try {
        $reader = $command.ExecuteReader();
        while ($reader.Read()) {
            $key = $reader.GetString(1)
            $previousScripts.Add($key) | Out-Null
        }

        $reader.Close();
        Write-Output "$(Get-Date) Finished querying previous scripts"
    }
    catch {
        $exceptionMessage = $_.Exception.Message;
        Write-Output "$(Get-Date) Error running SQL at with exception $exceptionMessage"
    }
}

然后:

$previousScripts = New-Object Collections.Generic.HashSet[string];
GetPreviousKeyMD5Hashes;

我根本不清楚这段代码 - 运行 GetPreviousKeyMD5Hashes 确实设置了 $previousScripts,但这对于在我之后修改它的人来说完全不清楚。我唯一的另一种选择(afaik)是将所有这些都排成一行,这也是不可读的。

最佳答案

is entirely redundant, when I can just call the function above, define someNum inside of it, and it will be available in the global scope.

否:函数在 范围内执行(除非您使用 . 对它们进行点源),因此在内部创建或分配变量一个函数是本地的。

Am I missing something or is it possible to write pure functions in Powershell that don't return everything inside the function?

是:隐式输出行为仅适用于其输出既不是捕获 - $var = ... - 也不是重定向 - ...> foo.txt

如果有语句碰巧产生输出而您想丢弃,请使用 $null = ..... . > $null

注意:... | Out-Null 原则上也有效,但通常性能较差,尤其是在早期的 PowerShell 版本中 - 谢谢,TheIncorrigible1 .

如果有状态消息您想编写而不将它们作为输出的一部分,请使用Write-Host 或者,最好是 Write-Verbose 或者,在 PSv5+ 中,Write-Information,但请注意后两者需要选择加入才能看到它们的输出在控制台中。
不要使用 Write-Output 写入状态消息,因为它写入成功输出流,其目的是输出 data ("return值(value)观”)。
this answer了解有关 PowerShell 输出流的更多信息。

因此,您的 JavaScript 代码的等价物是:

function sum($num1, $num2) {
  Write-Host "Adding $num1 and $num2..."  # print status message to host (console)
  $num1 + $num2 # perform the addition and implicitly output result
}

PS> $someNum = sum 1 2 # NOTE: arguments are whitespace-separated, without (...)
Adding 1 and 2...  # Write-Host output was passed through to console

PS> $someNum  # $someNum captured the success output stream of sum()
3

关于powershell - Powershell 中的显式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827905/

相关文章:

powershell - 在哪里可以找到 PowerShell ServerManager cmdlet 的退出代码及其含义的列表?

powershell - 从我的图像中获取 Azure VMImage

Powershell 写入错误不会填充 -ErrorVariable

javascript - 纯函数可以使用 `this` 改变其容器类内的其他属性吗?

powershell - 使用 PowerShell 在 Web 应用程序中启用应用程序日志记录

powershell - 如何使用PowerShell动态创建文件夹?

haskell - 如何在纯函数中跳过不必要的 IO?

java - 你会如何编写一个 "pure"函数来从列表中删除一个元素?

c++ - 成员方法调用同名但不同签名的虚方法

function - 幂等函数与纯函数相同吗?