1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just what I was looking for! Thanks Keith!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.