How do i allow powershell to accept an empty string for a named parameter?

Question:

I’m making a call to a powershell script:

I have other parameters, this is a bit watered down.

The PS script accepts the params :

When I run command i get:

Missing an argument for parameter ‘User’. Specify a parameter of type ‘System.String’ and try again.

I was under the assumption that AllowEmptyString would allow this?

Answer:

It doesn’t sound like you want a mandatory parameter at all. Making it mandatory will require input which makes the default value useless. However, let’s get back to the error your described.

The attribute works as expected. The problem is how you’re calling your script. Lets try the following code as a function and a script:

Demo:

However, when you run the last line in a PowerShell-session, then PowerShell will parse the string which results in an empty value (no quotes) for the parameter.

Powershell.exe is not intended to be used inside a PowerShell-process. You can fix this by calling scripts directly inside a PowerShell-process (second example), run PowerShell.exe … from cmd/run/scheduled task ++ (anywhere else) or by making sure PS doesn’t parse your arguments so it will actually input the quotes.

This can be done by escaping the quotes


Or by using --%

Source:

How do i allow powershell to accept an empty string for a named parameter? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply