Powershell参数字符串或文件 [英] Powershell parameters string or file
问题描述
我有一个脚本,希望用户能够输入字符串或使用脚本可以循环通过的文件(数组).
I have a script that i'd like the user to be able to enter a string or use a file(array) that my script can cycle through.
可以通过参数完成此操作吗?
Can this be done with a parameter?
我希望能够做这样的事情
I'd like to be able to do something like this
script.ps1 -file c:\users\joerod\desktop\listofusers.txt
或
script.ps1 -name "john doe"
推荐答案
可以,但是您需要选择使用位置参数时要使用的默认参数集,因为这两个参数的类型都是字符串,例如:
Sure, but you will need to pick the default parameterset to use when a positional parameter is used since the type of both parameters is a string e.g.:
[CmdletBinding(DefaultParameterSetName="File")]
param(
[Parameter(Position=0, ParameterSetName="File")]
[string]
$File,
[Parameter(Position=0, ParameterSetName="Name")]
[string]
$Name
)
if ($psCmdlet.ParameterSetName -eq "File") {
... handle file case ...
}
else {
... must be name case ...
}
DefaultParameterSetName必不可少的地方是当有人指定此名称时:
Where the DefaultParameterSetName is essential is when someone specifies this:
myscript.ps1 foo.txt
如果指定了默认参数集名称,PowerShell将无法确定应该使用哪个参数集,因为两个位置0参数的类型均相同.没有办法消除将参数放入哪个参数的歧义.
If the default parametersetname specified, PowerShell can't tell which parameterset should be used since both position 0 parameters are the same type [string]
. There is no way to disambiguate which parameter to place the argument in.
这篇关于Powershell参数字符串或文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!