3

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?

Blazey
  • 31
  • 1
  • 2

5 Answers5

10

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.

JPBlanc
  • 70,406
  • 17
  • 130
  • 175
1

Try this instead:

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

new-command

You don't need parentheses after the function name.

JoeG
  • 4,117
  • 1
  • 16
  • 15
  • His code works in PowerShell V2.0, but not in V1.0. In V1.0 the code gives exactly the error discribed – JPBlanc Jun 22 '11 at 05:07
1

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.

CosmosKey
  • 1,287
  • 11
  • 13
1

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

Community
  • 1
  • 1
Jing Li
  • 14,547
  • 7
  • 57
  • 69
0

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

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

NIMISHAN
  • 1,265
  • 4
  • 20
  • 29
kalaivani
  • 484
  • 1
  • 5
  • 8