如何在 PowerShell 函数中传递参数?
powershellmicrosoft technologiessoftware & coding
您可以在 PowerShell 函数中传递参数,要获取这些参数,您需要使用参数。通常,当您在函数外部使用变量时,实际上不需要传递参数,因为变量本身是公共的,可以在函数内部访问。但在某些情况下,我们需要将参数传递给函数,以下示例说明了如何编写相应的代码。
函数中传递的单个参数,
function writeName($str){
Write-Output "Hi! there .. $str"
}
$name = Read-Host "Enter Name"
writeName($name)
这里,我们将 $name 传递给 WriteName 函数,函数中的 $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

