Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 684 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I pass multiple parameters into a function in PowerShell?

#11
Function Test {
Param([string]$arg1, [string]$arg2)

Write-Host $arg1
Write-Host $arg2
}

This is a proper `params` declaration.

See *[about_Functions_Advanced_Parameters][1]*.

And it indeed works.

[1]:

[To see links please register here]




Reply

#12
There are some good answers here, but I wanted to point out a couple of other things. Function parameters are actually a place where PowerShell shines. For example, you can have either named or positional parameters in advanced functions like so:

function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[int] $Id
)
}

Then you could either call it by specifying the parameter name, or you could just use positional parameters, since you explicitly defined them. So either of these would work:

Get-Something -Id 34 -Name "Blah"
Get-Something "Blah" 34

The first example works even though `Name` is provided second, because we explicitly used the parameter name. The second example works based on position though, so `Name` would need to be first. When possible, I always try to define positions so both options are available.

PowerShell also has the ability to define parameter sets. It uses this in place of method overloading, and again is quite useful:

function Get-Something
{
[CmdletBinding(DefaultParameterSetName='Name')]
Param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Name')]
[string] $Name,
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Id')]
[int] $Id
)
}

Now the function will either take a name, or an id, but not both. You can use them positionally, or by name. Since they are a different type, PowerShell will figure it out. So all of these would work:

Get-Something "some name"
Get-Something 23
Get-Something -Name "some name"
Get-Something -Id 23

You can also assign additional parameters to the various parameter sets. (That was a pretty basic example obviously.) Inside of the function, you can determine which parameter set was used with the $PsCmdlet.ParameterSetName property. For example:

if($PsCmdlet.ParameterSetName -eq "Name")
{
Write-Host "Doing something with name here"
}

Then, on a related side note, there is also parameter validation in PowerShell. This is one of my favorite PowerShell features, and it makes the code inside your functions very clean. There are numerous validations you can use. A couple of examples are:

function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern('^Some.*')]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[ValidateRange(10,100)]
[int] $Id
)
}

In the first example, ValidatePattern accepts a regular expression that assures the supplied parameter matches what you're expecting. If it doesn't, an intuitive exception is thrown, telling you exactly what is wrong. So in that example, 'Something' would work fine, but 'Summer' wouldn't pass validation.

ValidateRange ensures that the parameter value is in between the range you expect for an integer. So 10 or 99 would work, but 101 would throw an exception.

Another useful one is ValidateSet, which allows you to explicitly define an array of acceptable values. If something else is entered, an exception will be thrown. There are others as well, but probably *the most useful* one is ValidateScript. This takes a script block that must evaluate to $true, so the sky is the limit. For example:

function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript({ Test-Path $_ -PathType 'Leaf' })]
[ValidateScript({ (Get-Item $_ | select -Expand Extension) -eq ".csv" })]
[string] $Path
)
}

In this example, we are assured not only that $Path exists, but that it is a file, (as opposed to a directory) and has a .csv extension. ($_ refers to the parameter, when inside your scriptblock.) You can also pass in much larger, multi-line script blocks if that level is required, or use multiple scriptblocks like I did here. It's extremely useful and makes for nice clean functions and intuitive exceptions.


Reply

#13
Because this is a frequent viewed question, I want to mention that a PowerShell function should use [approved verbs][1] (**Verb-Noun** as the function name).
The verb part of the name identifies the action that the cmdlet performs. The noun part of the name identifies the entity on which the action is performed. This rule *simplifies* the usage of your cmdlets for advanced PowerShell users.

Also, you can specify things like whether the parameter is *mandatory* and the *position* of the parameter:

function Test-Script
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]$arg1,

[Parameter(Mandatory=$true, Position=1)]
[string]$arg2
)

Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}


----------

To pass the parameter to the function you can either use the **position**:

Test-Script "Hello" "World"
Or you *specify* the parameter **name**:

Test-Script -arg1 "Hello" -arg2 "World"

You **don't use parentheses** like you do when you call a function within C#.

----------

I would recommend to *always* pass the parameter names when using more than one parameter, since this is more *readable*.

[1]:

[To see links please register here]




Reply

#14
Parameters in calls to functions in PowerShell (all versions) **are space-separated, not comma separated**. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if [`Set-StrictMode`][1] `-Version 2` or higher is active. Parenthesised arguments are used in .NET methods only.

function foo($a, $b, $c) {
"a: $a; b: $b; c: $c"
}

ps> foo 1 2 3
a: 1; b: 2; c: 3


[1]:

[To see links please register here]

Reply

#15
I don't see it mentioned here, but [**splatting**][1] your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using `Invoke-Expression`). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:

> **Note:** You can use positional splats with external commands arguments with relative ease, but named splats are less useful with external commands. They work, but the program must accept arguments in the `-Key:Value` format as each parameter relates to the hashtable key/value pairs. One example of such software is the `choco` command from the Chocolatey package manager for Windows.

## Splat With Arrays (Positional Arguments)
### Test-Connection with Positional Arguments
Test-Connection www.google.com localhost

### With Array Splatting
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentArray

> Note that when splatting, we reference the splatted variable with an `@` instead of a `$`. It is the same when using a Hashtable to splat as well.

## Splat With Hashtable (Named Arguments)
### Test-Connection with Named Arguments
Test-Connection -ComputerName www.google.com -Source localhost

### With Hashtable Splatting
$argumentHash = @{
ComputerName = 'www.google.com'
Source = 'localhost'
}
Test-Connection @argumentHash

## Splat Positional and Named Arguments Simultaneously
### Test-Connection With Both Positional and Named Arguments
Test-Connection www.google.com localhost -Count 1

### Splatting Array and Hashtables Together
$argumentHash = @{
Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentHash @argumentArray

[1]:

[To see links please register here]


Reply

#16
You call PowerShell functions without the parentheses and without using the comma as a separator. Try using:

test "ABC" "DEF"

In PowerShell the comma (,) is an array operator, e.g.

$a = "one", "two", "three"

It sets `$a` to an array with three values.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through