Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Function arguments are all being passed in the first argument

Tags:

powershell

When I run this code in PowerShell:

function Check-Missing([String] $arg1, [String] $Arg2, [String] $Arg3)
{
    echo $arg1
    echo "----------"
    echo $arg2
    echo "----------"
    echo $Arg3
}

$titi = "123"
$toto = "456"
$tata = "789"

Check-Missing($titi,$toto,$tata)

I get this output:

123 456 789
----------

----------

I simply cannot get my head around it :-( what is going on here ?! And wait, it gets better:

function Start-App{

    Param(
    [parameter(Mandatory=$true)]
    [System.Object] $Arg1,
    [System.Object] $Arg2,
    [System.Object] $Arg3 
    )

    echo $arg1
    echo "---"
    echo $arg2
    echo "---"
    echo $Arg3

}

$a = "abc"
$b = "bcd"
$c = "cde"

Start-App($a.ToString(),$b.ToString(),$c.ToString())

This code gives me the following:

abc
bcd
cde
---
---

I also tried this:

function Start-App{

    Param(
    [parameter(Mandatory=$true)]
    [String] $Arg1,
    [String] $Arg2,
    [String] $Arg3 
    )

    echo $arg1
    echo "---"
    echo $arg2
    echo "---"
    echo $Arg3

}

$a = "abc"
$b = "bcd"
$c = "cde"

Start-App($a.ToString(),$b.ToString(),$c.ToString())

But get this silly error which make absolutely no sense since I cast the variables to a string before passing them to the function:

Start-App : Cannot process argument transformation on parameter 'Arg1'. Cannot convert value to type System.String.

I seems that whatever I do, the parameters are passed as one (in the first parameter which is not what I want)...How can I ensure that parameters are passed through correctly ?!

like image 950
pussinboots1992 Avatar asked Oct 25 '25 21:10

pussinboots1992


1 Answers

as per comment from Lee, you may want to read up on how functions in PowerShell are meant to be called:

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7

If you change your function call to this, it works as expected:

Check-Missing $titi $toto $tata

Additionally in your second example, because you are using advanced parameters you can explicitly call them (allowing them to be out of order or other funky stuff):

Start-App -Arg2 $b -Arg1 $a -Arg3 $c
like image 133
retryW Avatar answered Oct 29 '25 05:10

retryW