Powershell parameters string or file

大城市里の小女人 提交于 2019-12-11 12:06:36

问题


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 

or

script.ps1 -name "john doe"

回答1:


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 ...
}

Where the DefaultParameterSetName is essential is when someone specifies this:

myscript.ps1 foo.txt

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.



来源:https://stackoverflow.com/questions/24374622/powershell-parameters-string-or-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!