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

26 Comments

  • 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)
    }

  • Thanks for the clarifation

    man I fought with this for a day...

    I want to pass args as in c++


    foo(2,20)

    but in Pshell it's

    foo "2" "20"

    provided that foo is written to accept params:

    funtion foo {
    param([int]=$arg1,[int]=$arg2)
    write-host "$arg1, $arg2"
    }



    SO, now I have it cleared up, but still, my c++ side wants to call this like foo(2,20).

    Anyway, thanks again!




  • Great, just what I was looking for. Thanks.

  • yeah me too,i was going nuts over this !

  • Thx,

    I was fighting with PShell passing arguments, had a tuff time for half a day.

    i was going mad what is wrong with it.

    Anyways thanks a lot :)

  • hello to all,

    i don't understand all
    pls i need en fonction
    (or parameter) like:

    function var {var1,var2,var3, ....
    if ([int64]var -lt 0)
    $var.style.color="#E30000";}

    thnx for any help
    AA

  • That sucked! It took me 4 hours of my life to figure this out....and I cannot get them back :(

  • Thats because powershell; nice as it is; is also pointlessly and randomly obscurely different and bizarre just for the sake of it.
    Its like the people who designed it had been locked away by Microsoft for forty years in a commune somewhere; isolated from the whole history of the computing universe; and then were told to create powershell untainted from anything that ever existed before.

  • function fnc
    {
    param ( $str )
    $str = $str + "aaa"
    #write-host $str
    return $str
    }

    cls
    [string]$str = "bo"

    fnc $str

    write-host $str
    +++++++++++++++++++++++++
    I would expect $str to be "boaaa", but it still is "bo"

  • The variable $str needs to be a reference variable of type [ref] in order for it to be called by reference. Also need to use the .value property and the return $str is unnecessary. Try this.

    function fnc
    { param ( [ref]$str )
    $str.value = $str.value + "aaa"
    #return $str
    }
    cls
    [string]$str = "bo"

    fnc ([ref]$str)

    write-host $str

  • Important missing point: You simply can't call the function before you had written down that into the script, for instance:

    this does works:
    function foo(){Write-Host "foo"}
    foo()

    this doesn't works:
    foo()
    function foo(){Write-Host "foo"}

    Knowing this may save some time, don't you think?

  • How can you call a powershell function that has parameters that is in a different script??

    Thanks for the help!

  • Thanks a lot for the comment on how to call a function. I'm a couple hours old in powershell and I'm quite surprised by the some of the syntax.

    HaGD

    Phil

  • Thanks a lot.This really help me from tearing half of my hair out.the other half I tore up already trying to pass the arguments in the function.

  • This helped - the C# mindeset kept thinking put parens and then args.

    so now it is something like

    function fname {
    param(
    [string]parmOne=$(throw "parmOne required"),
    [int]parm2
    )## End of Parms and start of function


    } #end brace of function

    I tried to pass 2 args with and without parens and it was not working.

    fname -parmOne "Data" -parm2 256

    I had to pass the parameters as NAMED variables. And then it worked.

    Thanks - your post was the first in Google results.

  • How about some how-to on passing a boolean (i.e. Switch-type) param into a .ps1 script file?

  • Thanks!
    I spent more than 2h trying to sort this out.

    Kirill

  • Thanks a lot!

    really strange behavior !!

    @ajc (and others try passing boolean params):
    the type should be "bool"
    Param(
    [string] $VM,
    [bool] $Suspend
    )
    this works

  • Yes there should realize the reader to RSS my feed to RSS commentary, quite simply

  • Thanks for the concepts of parameter passing with functions.

  • man .. thanks so much

  • Thnx Jeovane!!!
    It's so annoying to find out that you simple CAN'T CALL A FUNCTION IN POWERSHELL PRIOR TO IT'S CODE!
    In other words - 1-ST WRITE THE FUNCTION, THAN CALL IT!
    Thnx again, I've spent almost an hour trying to figure out why I can't call it.

    Microsoft, it's shame on you that you couldn't implement a full OO coding experience, this issue reminds me the very old & dark PASCAL ages!

  • So-so. Something was not impressed.

  • Another strangeness with PowerShell then...

    I, as a normal programmer in lots of OS'es and scriptlanguages can't really understand the almost backbreaking way they done some things in this scriptlanguage... but at othertimes it's very powerful... just annoyingly quirky in other ways...

    but thanks for this tip, useful...

  • So I've got another wrinkle for you: positional versus named parameters and default arguments values...

    ### script block ###

    function foo ([string] $a, [string]$b = "bar", [bool] $c = $false)
    {
    Write-Host "a:", $a, "; b:", $b, "; c:", $c
    }

    foo "hello"
    # Output: a: hello ; b: bar ; c: False
    # "hello" is the first positional parameter and it is assigned to the first argument 'a'.
    # All others are left with their default value

    foo "Hello" "World!" $true
    # Output: a: Hello ; b: World! ; c: True
    # "hello" is the first positional parameter and it is assigned to the first argument 'a'.
    # "World!" is the second positional parameter and it is assigned to the second argument 'b'.
    # $true is the third positional parameter and it is assigned to the third argument 'c'.

    foo "Hello" -a "World!" $true
    # Output: a: World! ; b: Hello ; c: True
    # Named arguments are processed first, no matter what order that arguments are given in
    # '-a "World!"' is a named parameter is is processed first and so 'a' becomes "World!"
    # "Hello" is the first positional parameter and is assigned to the first _unassigned_ argument, which in this case is 'b'
    # $true is the second positional parameter and is assigned to the second unassigned argument: 'c'

    foo "Hello" -c $true
    # Output: a: Hello ; b: bar ; c: True
    # Named arguments are processed first, no matter what order that arguments are given in
    # '-c $true' is a named parameter is is processed first and so 'c' becomes $true
    # "Hello" is the first positional parameter and is assigned to the first _unassigned_ argument, which in this case is 'a'


    foo -b "World!"
    # Output: a: ; b: World! ; c: False
    # Named arguments are processed first, no matter what order that arguments are given in
    # '-b "World!"' is a named parameter is is processed first and so 'b' becomes "World!"
    # All other arguments get their default values. Since 'a' is unassigned, it is null which is rendered as nothing to the console.

    ### script block ###

  • Please note:
    f "A", "B" means you provide function f with an array of two string members as first positional parameter, the second positional parameter is empty
    f "A" "B" means you provide function f with string "A" as first positional parameter and string "B" as second positional parameter
    f ,"A" "B" means you provide function f with an array consisting of only one member (string "A") as first positional parameter and string "B" as second positional parameter

Comments have been disabled for this content.