Anzurio
Anzurio

Reputation: 17014

When not supplying a Mandatory parameter make the prompt not interpret it as a string

I have a mandatory parameter like:

[Parameter(Mandatory=$true)]$foo

I do want PowerShell to prompt to supply one if the user failed to do so. However, I would like to be able to supply a variable; that is if $bar is supplied, it does not bind it as $foo = "$bar".

Upvotes: 4

Views: 212

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59031

You could use the ExpandString function to expand that variable like:

function Test-Param
{
    Param(
        [Parameter(Mandatory=$true)]$foo
    )

    $foo = $ExecutionContext.InvokeCommand.ExpandString($foo)

    Write-Host $foo   
}

You can test it using:

$bar = "hello"
Test-Param

Now just pass $bar to the prompt and you will get hello printed.

Upvotes: 4

Related Questions