powershell function with 2 parameters , parameters are set to the first parameter

rob m 256 Reputation points
2023-04-12T17:48:27.19+00:00

I cal a funtion with 2 parameters 1 string the other an int but once in the function the functions first parameter shows up as the first parameter with the 2nd int concatenated to it see image below of VSCODE while debugging User's image

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,329 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 45,906 Reputation points
    2023-04-12T19:23:28.37+00:00

    Without seeing the code that invokes the Create-User function it really isn't possible to say what the exact problem is, but I suspect it's that you're passing the parameters in a comma-separated list (as you would in C#, C++, C, and many other programming languages. In PowerShell that's a mistake (a common one, too). By doing so you create an array that's passed to the function. PowerShell separates positional parameters with spaces, not commas.

    This demonstrates the problem:

    function Create-User{
        param(
            [string]$name,
            [int]$operator
        )
        Write-Host "`t`$name = '$name'"
        Write-Host "`t`$operator = '$operator'"
        if($operator -eq 1){
            Write-Host "CORP - operator = $operator"
        }
        else{
            Write-Host "not an CORP - operator = $operator"
        }
    }
    Write-Host "Passing individual parameters"
    Create-User nsalehem 0
    Write-Host "---------------"
    Write-Host "Passing parameters as an array"
    Create-User ndalehem,0
    
    0 comments No comments