PowerShell: calling a function with parameters

I just started with PowerShell to do some complex scripting. As a beginner in this new language I will probably run into all the quirks that the language has, but hey thats the fun with learning something new. The first quirk: calling a function with parameters.

function f([string]$a, [string]$b)
{
  Write-Host "a:", $a, " b:", $b
}

f("hello", "world") # Results in: a: hello world b:
f "hello" "world"   # Results in a: hello b: world

If you put something between parentheses, it is executed as an expression first.

For more information on what you can do with functions, execute the following command in your PowerShell: Get-Help about_function

Published Wednesday, November 29, 2006 10:44 AM by svdoever
Filed under: ,

Comments

Saturday, August 18, 2007 10:07 AM by CumpsD

# re: PowerShell: calling a function with parameters

I'm sure you're going to love this sample output:

PS C:\> function f([string]$a, [string]$b)

>> {

>>   Write-Host "a:", $a, " b:", $b

>> }

>>

PS C:\> f("A", "B")

a: A B  b:

PS C:\> f "A", "B"

a: A B  b:

PS C:\> f "A" "B"

a: A  b: B

PS C:\> f("A", "B") "C"

a: A B  b: C

PS C:\>

Your behavior isn't just from the parentheses, but due to the commas.

Friday, September 14, 2007 4:22 PM by Daniel

# re: PowerShell: calling a function with parameters

PowerShell is a bit funky.. When you create a function and you want to supply parameters, the following format applies:

function fname {

  param([string]$a, [int]$b) # the two parameters.

  write-host ("a = " + $a)

  write-host ("b = " + $b)

}

Leave a Comment

(required) 
(required) 
(optional)
(required)