如何在 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