如何在 PowerShell 函式中傳遞引數?
你可以傳遞指定的引數到 PowerShell 函式,若要捕獲這些引數,你需要使用 argument。通常,當你在函式外使用變數時,你不必傳遞 argument,這是因為變數本身就是公開的,並且可以在函式內訪問。但在某些情況下,我們需要將引數傳遞給函式,下面的示例解釋瞭如何為其編寫程式碼。
傳入函式的單一引數:
function writeName($str){
Write-Output "Hi! there .. $str"
}
$name = Read-Host "Enter Name"
writeName($name)在這裡,我們傳入函式 WriteName 中的 $name,並且函式中的 $str 變數捕獲了引數,因此你可以在函式內使用 $str 來獲取值。
輸出
Enter Name: PowerShell Hi! there .. PowerShell
要將多個值傳遞給函式,你不能夠使用其他程式語言方法將多個值傳遞給引數。以下示例為錯誤寫法:
writeName($name1,$name2)
相反,在 PowerShell 中,你可以使用以下提及的方法傳遞多個值。
示例
writeName $name1 $name2
function writeName($str1,$str2){
Write-Output "Hi! there .. $str1 $str2"
}
$name = Read-Host "Enter Name"
$surname = Read-Host "Enter Name"
writeName $name $surname輸出
Enter Name: Harry Enter Name: Potter Hi! there .. Harry Potter
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP