2

I am working from the command line. Let's say my example looks like this:

Param(
  [Parameter()] [string]$greeting="HelloWorld"
)

From the commandline I can do this: mygreeting
And it will output HelloWorld

Or I can do this: mygreeting -greeting="whatever"
And it will output whatever

Why can't I type this?:

mygreeting -greeting

without getting an error that the argument is missing?

In the code I want to be able to basically say:
If greeting is specified but has no value then set the value conditionally based on other things
If greeting is not specified use the default value

1
  • What do you mean by "no value"? Like if someone enters mygreeting -greeting ""? If you pass in a flag, I think it requires something Commented Jan 6, 2017 at 22:44

2 Answers 2

1

This is by design. In PowerShell you are passing an argument by specifying the name of the parameter followed with the value you want to pass (except if its a switch or you using positional parameters where you only pass the value).

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

Comments

1

you can use this :

function test-test {
    [CmdletBinding()] 
    Param (
    [parameter(Position = 0)]
    [string]$greetings = "hi world"
    )

    $greetings
}

to set value about your parameter and u can call it like this :

test-test "something"

or

test-test -greetings "something"

but you cant run it like parameter="value"

if you want to use this you should use :

test-test ($greetings = "ssss")

like this. but actually this $greetings not the same of variable in your function because have grater oscope than youre function.

Comments

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.