BlackHatSamurai
BlackHatSamurai

Reputation: 23483

Multiple parameters put into one variable in PowerShell

I am trying to pass in 2 argument to a PowerShell script which calls invoke-command and I'm trying to pass in multiple parameters. But when I do, it seems like both parameters are put into a single variable and I'm wondering why.

Here is the code for both programs:

POC.ps1:

param($filename, $user)

echo $filename
echo "This"
echo $user

$responseObject = Invoke-Command CAPTESTPK01 -FilePath .\validatePath.ps1  -ArgumentList($filename, $user) -AsJob 




while($responseObject.State -ne "Completed")
{

}

$result = Receive-Job -Id $responseObject.Id -Keep
echo $result

validatPath.ps1:

Param([string] $filename,
      [string] $user)

function ValidatePath( $filename, $user, $fileType = "container" )
{
    Write-Host "This is the file name: $filename"
    echo "This is user: $user"
    $fileExist = $null
    if( -not (test-path $filename -PathType $fileType) )
    {               
        throw "$user, the path $filename does not exist!"

    }
    else
    {
         Write-Host "This is the second part"
         echo $filename found!
    }
     Write-Host "This is the third part"
    return $fileExist
}


try
{

    ValidatePath($filename, $user)
}
catch
{
    $e = $_.Exception
    echo $e
}

Here is the output:

C:\Users
This
Blaine
This is the file name: C:\Users Blaine <--- This indicated both arguments are in one variable
This is user: 
This is the second part
This is the third part
C:\Users
Blaine

Upvotes: 1

Views: 3766

Answers (1)

Lars Truijens
Lars Truijens

Reputation: 43595

Arguments to PowerShell functions should not be put in parenthesis when called. It should be ValidatePath $filename $user. What you have written results in calling ValidatePath with just one parameter and $filename being an array of two values, namely the filename and the user.

BTW: When calling .Net methods in PowerShell you do need the parenthesis. :)

Upvotes: 2

Related Questions