简体   繁体   English

在Powershell脚本中传递可选参数

[英]Passing optional arguments in Powershell script

I'm trying to write a code that would check if arguments exist and take action accordingly. 我正在尝试编写代码来检查参数是否存在并采取相应的措施。 The code would need to be flexible to run with or without arguments when the script is called. 调用脚本时,代码需要灵活地运行,无论有无参数都可以运行。
For example: 例如:

if (arg[0] -And arg[1])
{
    $argOne = arg[0]
    $argTwo = arg[1]
}
else
{
    $argOne = "One"
    $argTwo = "Two"
}

This code is obviously wrong because I'm not sure how to check if arguments exist in Powershell. 这段代码显然是错误的,因为我不确定如何检查Powershell中是否存在参数。 In python, there is the functionality of sys.argv that stores all arguments into an array. 在python中,有sys.argv的功能,可将所有参数存储到数组中。 I could then do a try-except to check if the arguments exist. 然后,我可以做一个try-except来检查参数是否存在。 Can I do something similar in Powershell? 我可以在Powershell中做类似的事情吗?
I did some research and param was advised to use to handle arguments but I don't think param could handle no arguments being passed to the script. 我进行了一些研究,建议使用param处理参数,但是我认为param无法处理传递给脚本的参数。

Turns out I was wrong about param ! 原来我在param错了! Came across this which was very helpful. 遇到了这一点 ,这非常有帮助。

param($one, $two)

if ($one -And $two)
{
    $argOne = $one
    $argTwo = $two
}
else
{
    $argOne = "One"
    $argTwo = "Two"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 arguments 传递给 Powershell 脚本 - Passing arguments to Powershell script 将参数传递给从 powershell 5 调用的 powershell 7 脚本 - Passing arguments to powershell 7 script invoked form powershell 5 VSTS 将变量传递到 Azure PowerShell 脚本参数 - VSTS passing variables into Azure PowerShell Script Arguments 通过传递参数从另一个PowerShell脚本调用一个PowerShell脚本 - Invoke one PowerShell script from Another PowerShell script with passing arguments 将%*从批处理脚本作为$ args传递到Powershell脚本时转义参数 - Escaping arguments when passing %* from batch script as $args to powershell script 将命令行参数从Powershell脚本传递到python脚本 - Passing command line arguments from powershell script to a python script 如何使用Powershell下载脚本文件然后通过传入参数执行它? - How to use Powershell to download a script file then execute it with passing in arguments? 将cmd行参数传递给powershell脚本-如果没有争论,如何退出 - passing cmd line arguments to powershell script - how to exit if no arguements 在 PowerShell 脚本中传递 arguments 时尝试转义括号 - Trying to escape parenthesis when passing arguments in a PowerShell script 使用脚本打开另一个 powershell 实例,同时将 arguments 传递给新实例 - opening another instance of powershell with a script while passing the arguments to the new instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM