PowerShell是用于管理Windows系统的完整脚本和编程语言。与其他编程语言一样,PowerShell支持函数和参数。PowerShell有不同的用例,比如创建用户、向数据库添加一些数据甚至复制数据。条款 parameter
和 argument
通常可以互换使用。所以在本教程中,我们将参考一个或多个参数。
读取单个参数/参数
从PowerShell中的命令行接口读取单个参数或参数的最基本情况。$args[]数组可用于获取提供的参数或参数。作为一个数组,它存储作为参数提供的单个或多个项。第一项以索引号0存储。
$parameter1 = $args[0]
write-host $parameter1
我们将调用名为MyScript.ps1的PowerShell脚本,并提供“windowstect.com”作为参数。
.MyScript.ps1 "windowstect.com"
![图片[1]-如何在PowerShell中传递参数和参数?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2021/05/windowstect_image-20.png)
读取多个(两个或更多)参数/参数
数组$args[]可用于读取多个参数。这些参数可以是两个或多个。数组$arg[]中的每个项都根据提供的序列存储了一个参数。在下面的示例中,我们将从MyScript.ps1的命令行界面读取3个参数。
$param1=$args[0]
$param2=$args[1]
$param3=$args[2]
write-host $param1
write-host $param2
write-host $param3
我们提供“windowstect.com”、“linuxtect.com”和“wisetut.com”作为3个参数。
.MyScript.ps1 "windowstect.com" "linuxtect.com" "wisetut.com"
![图片[2]-如何在PowerShell中传递参数和参数?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2021/05/windowstect_image-21.png)
读取大量参数
在某些情况下,我们可能需要读取大量参数并存储其中一些特定的变量等。可以使用for循环来读取一组参数。提供的每个参数都使用for循环进行迭代。提供的参数计数存储为$args.count变量。
for ( $i=0; $i -lt $args.count; $i++){
write-host $args[$i]
}
在下面的示例中,我们将使用不同的参数计数多次调用MyScript.ps1 PowerShell脚本。每次它都能正常工作并处理多个参数。
.MyScript.ps1 "windowstect.com" "linuxtect.com".MyScript.ps1 "windowstect.com" "linuxtect.com" "wisetut.com" "pythontect.com" "poftut.com"
![图片[3]-如何在PowerShell中传递参数和参数?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2021/05/windowstect_image-22-1024x193.png)
读取命名参数/参数
为了使PowerShell脚本更加专业和易于阅读,可以使用命名参数从命令行读取参数。命名参数使用函数param()为不同的参数指定名称。如果为指定的命名参数设置适当的参数,则序列很重要。
param($name,$surname)
write-host "Name is $name"
write-host "Surname is $surname"
在下面的示例中,我们将使用指定给名为 $name
和 $surname
. 函数 param()
用于自动设置它们。
.MyScript.ps1 "İsmail" "Baydan"
![图片[4]-如何在PowerShell中传递参数和参数?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2021/05/windowstect_image-23.png)
或者,可以使用函数中定义的名称指定已命名的PowerShell参数 parameter()
. 唯一的变化是$符号替换为-。
.MyScript.ps1 -surname "Baydan" -name "İsmail"
![图片[5]-如何在PowerShell中传递参数和参数?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2021/05/windowstect_image-24.png)
设置默认参数/参数值
在PowerShell中使用参数的另一个好做法是为参数设置默认值。可以为默认值指定参数,如果在调用PowerShell脚本时未指定参数,则使用默认值。在下面的示例中,我们将调用 MyScript.ps1
并提供参数 -name
不提供 -surname
.
param($name,$surname="Baydan")
write-host "Name is $name"
write-host "Surname is $surname"
![图片[6]-如何在PowerShell中传递参数和参数?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2021/05/windowstect_image-25.png)
相关文章: Windows磁盘管理工具