如何在 PowerShell 中返回值

一般而言,return
關鍵字會結束一個函數、腳本或腳本區塊。因此,例如,我們可以使用它在特定時刻離開一個範疇、返回一個值,或表示該範疇的結束已達到。
然而,在 Windows PowerShell 中,使用 return
關鍵字可能會讓人有些困惑,因為你的腳本可能會打印出你意想不到的輸出。
本文將討論 return
關鍵字的工作原理以及如何在 Windows PowerShell 中正確使用它們。
在 PowerShell 中使用 return
關鍵字
下面的腳本區塊是 return
關鍵字語法的基本形式。
return <expression>
return
關鍵字可以單獨出現,或者後面可以跟一個值或表達式。單獨的 return
關鍵字將命令行返回到其先前的調用點。
return
return $a
return (1 + $a)
下面的例子使用 return
關鍵字在滿足條件時退出函數。在這個例子中,奇數不會被乘以,因為返回語句在那個語句執行之前就已經執行了。
function MultiplyOnlyEven {
param($num)
if ($num % 2) { return "$num is not even" }
$num * 2
return
}
1..10 | ForEach-Object { MultiplyOnlyEven -Num $_ }
輸出:
1 is not even
4
3 is not even
8
5 is not even
12
7 is not even
16
9 is not even
20
從更本地的編程角度來看,Windows PowerShell 的返回語義是令人困惑的。我們需要考慮兩個主要概念:
- 所有輸出都被捕獲並返回。
- return 關鍵字表示邏輯退出點。
話雖如此,以下幾個腳本區塊將返回 $a
變量的值。
具有表達式的 return 關鍵字:
$a = "Hello World"
return $a
不帶表達式的 return 關鍵字:
$a = "Hello World"
$a
return
在第二個腳本區塊中也不需要 return
關鍵字,因為在命令行中調用變量將明確返回該變量。
在 PowerShell 的管道中返回值
當您從腳本區塊或函數返回一個值時,Windows PowerShell 會自動逐一推出成員並將它們推送到管道中。這種用法的原因是 Windows PowerShell 的一次處理一個的方式。
以下函數演示了這個思想,將返回一個數字數組。
function Test-Return {
$array = 1, 2, 3
return $array
}
Test-Return | Measure-Object | Select-Object Count
輸出:
Count
-----
3
當使用 Test-Return
cmdlet 時,下面函數的輸出被管道傳遞到 Measure-Object
cmdlet。該 cmdlet 將計數管道中的對象數量,並且在執行時,返回的計數為三。
要使腳本區塊或函數僅返回單個對象到管道中,可以使用以下方法之一:
在 PowerShell 中利用一元數組表達式
利用一元表達式可以將返回值作為單個對象發送到管道中,如下面的例子所示。
function Test-Return {
$array = 1, 2, 3
return (, $array)
}
Test-Return | Measure-Object | Select-Object Count
輸出:
Count
-----
1
在 PowerShell 中使用 Write-Output
和 NoEnumerate
參數
我們還可以使用帶有 -NoEnumerate
參數的 Write-Output
cmdlet。下面的例子使用 Measure-Object
cmdlet 計算從示例函數通過 return
關鍵字發送到管道中的對象。
示例代碼:
function Test-Return {
$array = 1, 2, 3
return Write-Output -NoEnumerate $array
}
Test-Return | Measure-Object | Select-Object Count
輸出:
Count
-----
1
另外一種強制管道僅返回單個對象的方法是在 PowerShell 版本 5 中引入的,我們將在文章的下一部分中討論。
在 PowerShell 5 中定義類
隨著 Windows PowerShell 版本 5.0,我們現在可以創建和定義我們的自定義類。將您的函數更改為類,return
關鍵字將僅返回其前面的單個對象。
示例代碼:
class test_class {
[int]return_what() {
Write-Output "Hello, World!"
return 1000
}
}
$tc = New-Object -TypeName test_class
$tc.return_what()
輸出:
1000
如果上述類是函數,它將返回所有存儲在管道中的值。
輸出:
Hello World!
1000
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn