New-Object PSObject works in PS script but not inside a function

Joe 21 Reputation points
2022-02-16T02:47:08.003+00:00

I am seeing strange results when using New-Object PSObject inside a PS function. I have searched and can't find any clues to why.

This works:

$b = "ValueB"
$c = "ValueC"

$H = @{
b = $b
c = $c
}

$z = $h | ConvertTo-Json

Write-Host $z

Output:

{
"c": "ValueC",
"b": "ValueB"
}

This does not work:

Function A {

PARAM ($b, $c)

$H = @{
b = $b
c = $c
}

$z = $h | ConvertTo-Json

Write-Host $z

}

A "ValueB", "ValueC"

Output:

{
"c": null,
"b": [
"ValueB",
"ValueC"
]
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,504 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 107.8K Reputation points MVP
    2022-02-16T07:23:26.773+00:00

    Hi @Joe ,

    here the function works. It looks like you have to call the function a little different:

    Function A {  
      PARAM ($b, $c)  
      $H = @{  
        b = $b  
        c = $c  
      }  
      $z = $h | ConvertTo-Json  
      Write-Host $z  
    }  
      
    # This works  
    A -b ValueB -c ValueC  
    # This works as well  
    A ValueB ValueC  
    

    Output looks like this in both cases:

    174789-image.png

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 46,551 Reputation points
    2022-02-16T15:51:14.653+00:00

    PowerShell does not use a comma separator in a parameter list when calling PowerShell functions. Just use spaces, or use the parameter names followed by the value (e.g., A -b 'ValueB' -c 'ValueC'. OR A -c 'ValueC' -b 'ValueB')

    If you use a comma you're creating a list. I.e., A "ValueB", "ValueC" creates a two element list consisting of two strings. The function "A" receives only one parameter $b (in parameter position zero), and nothing for parameter $c.

    The ConvertTo-Json emits a value of "null" because the variable $c contains the value $null, and a list (or array) for variable $b.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.