Blazey
Blazey

Reputation: 31

Powershell Cmdlet with Mandatory Parameters

I'm trying to create a simple powershell cmdlet that would have a few mandatory parameters. I've found the following code for doing so however, I cannot get it to execute:

function new-command() {
    [CmdletBinding()]
    PARAM (
        [Parameter(Mandatory=$true)]
        [string]$Name
    )
}

new-command

Returns the following error:

Missing closing ')' in expression." Line: 5 Char: 3 + [ <<<< string]$Name

What am I doing wrong?

Upvotes: 3

Views: 8521

Answers (5)

kalaivani
kalaivani

Reputation: 604

Try below syntax and also kindly check whether have missed any double quotes or brackets.

Param([parameter(Mandatory=$true, HelpMessage="Path to file")] $path)

Upvotes: 0

Jing Li
Jing Li

Reputation: 15116

You'll have the same error message even with Powershell v2.0 if Param(...) hasn't been declared at the beginning of the script (exclude comment lines). Please refer to powershell-2-0-param-keyword-error

Upvotes: 1

CosmosKey
CosmosKey

Reputation: 1317

In PS 2.0 mandatory parameters are controlled through the CmdLetBinding and Parameter attributes as shown in the other answers.

function new-command {
    [CmdletBinding()]
    PARAM (
        [Parameter(Mandatory=$true)]
        [string]$Name
    )
    $Name
}

new-command

In PS 1.0 there are not direct constructs for handling mandatory attributes but you can for example throw an error if a mandatory parameter hasn't been supplied. I often use the following construct.

function new-command {
    param($Name=$(throw "Mandatory parameter -Name not supplied."))
    $Name
}

I hope this helps.

Upvotes: 1

JPBlanc
JPBlanc

Reputation: 72680

The explanation is that you are running this script in PowerShell V1.0 and these function attributes are supported in PowerShell V2.0. Look at $host variable for you PowerHhell version.

Upvotes: 10

JoeG
JoeG

Reputation: 4247

Try this instead:

function new-command {
    [CmdletBinding()]
    PARAM (
        [Parameter(Mandatory=$true)]
        [string]$Name
    )
}

new-command

You don't need parentheses after the function name.

Upvotes: 1

Related Questions