开发者

Powershell Cmdlet with Mandatory Parameters

I'm trying to create a simple powershell cmdlet that would h开发者_如何学运维ave 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?


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.


Try this instead:

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

new-command

You don't need parentheses after the function name.


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.


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


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜