Skip navigation

Parameters in "Advanced Functions"

Although I still like to call them "Script Cmdlets," the official name is "Advanced Functions," and you'll find official help on them in topics like about_advanced_functions* - be sure to include that wildcard, because there are a few topics you'll want to read.

Once confusing part for these has always been declaring their parameters. A normal function contains parameters like this:

function MyFunction {
 param ( $computername, $force, $mode )
 # function code goes here
 # computer name input is in $computername variable, etc
)

You can run such a function in one of two ways. First, provide parameter values in the correct order:

MyFunction localhost $true ReadOnly

Or, you can specify parameters by name:

MyFunction -computername localhost -force $true -mode ReadOnly

What you can't do is have pipeline input automatically attach (or bind) to these parameters, nor can you mark them as mandatory, specify data validation, and so on. With an advanced function's cmdlet-style parameter declaration, however, you CAN do all of these things:

function MyFunction {
 [CmdletBinding()]
 param (
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string[]]$computername
 )
 # still access computer name in $computername
}

All we've done here is add a few attributes to the parameter. Declaring the parameter type (string[]) is actually still optional, and you could have done that in the simpler style of function, too. Now, we get a third way we can run the function: Assuming we have a text file that contains one computer name per line, for example:

gc computers.txt | MyFunction

Because those computer names are strings, they will bind ByValue to our -computerName parameter. If someone tries to run our function without specifying a -computername parameter, the function will not run immediately, because we've marked that parameter as mandatory. 

You can see some additional parameter examples at http://www.windowsitpro.com/blogs/PowerShellwithaPurpose/tabid/2248/entryid/12823/Default.aspx.

So tell me: What else about these parameters do you find confusing? Anything? 

Want more PowerShell articles, along with FAQs and more? Visit http://windowsitpro.com/go/DonJonesPowerShell.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish