Link to Parent: PowerShell - Deep Dive and Best Practice
Reference for dealing with parameter attributes WORK IN PROGRESS
text
These are used to modify how individual parameters are managed. They are applied in the following form:
Param(
[parameter(attribute=value, attribute=value)]
[
string
]
$variable
)
This is used to make a parameter required. It takes a true or false value. The default is false so typically this is only applied if you want to make a parameter required.
[parameter(Mandatory=$
true
)]
If a function is called with parameters and the parameter isn't assigned by name, its done by position, and the Position parameter attributes value indicates which value is assigned to which parameter. This is 0 based assignment.
Function Get-NameAndAge {
[parameter(Position=0)]
$Name,
[parameter(Position=1)]
int
$age
write-host
"Name: $name Age: $age"
}
#can be called the normal way,
Get-NameAndAge -Name Justin -age 30
#or, because we've defined position values we can call it without named parameters
Get-NameAndAge Justin 30
This is used to define different combinations of parameters. For example if you have a function that can take a username, or a computername and action, you could say that if you provide a computername then the user can not also provide a username.
function Invoke-OnElement {
param(
[parameter(parametersetname=
"byname"
$username,
[parameter(parametersetname="bycomputer)]
$computername,
$description
switch
($PsCmdlet.ParameterSetName)
{
{ Set-NameProperty -user $username -description $description}
"bycomputer"
{ Set-ComputerProperty -computer $computername -description $description}
This is used to accept data from the pipeline. This part can actually get a little tricky in how you design your function. There are two uses cases for something like this, one being passing values over the pipe or using them directly. "serverA","serverB" | Test-Server or Test-Server -ComputerName "serverA","serverB" In order to have both of these work you'll need to define your function in this way.
function Test-Server {
[parameter(ValueFromPipe=$
[]]
$computername
PROCESS
foreach
($system
in
$computername)
#run tests
In order for the function to handle the items from the pipe, you need to use the begin/process/end blocks (only process shown above) but in order for it to handle an array passed in to the param you need the foreach loop. This doesn't make for the prettiest function but this is the setup for it.
Carsten Siemens edited Revision 5. Comment: Added tag: has TOC. Fixed misspellings
Ed Price - MSFT edited Revision 3. Comment: Title edit, per guidelines
jrich edited Original. Comment: headers created