1

I am trying to pass a parameter through a function in powershell but it is not working

Code

function test($test1, $test2)
{
 $details = @"
{ "updateDetails": [
    {
        "customer": "John",
        "rank": $test1
    },
    {
        "school": "western",
        "address": $test2
    }
    ]
}
"@
return $details
}
test 0 florida

Current issue

{ "updateDetails": [
    {
        "customer": "John",
        "rank": 
    },
    {
        "school": "western",
        "address": florida
    }
    ]
}

I tried running test but the value 0 is not filled in the details json, florida is filled in correctly. How can I replace the two values. Also how can florida be in string

2 Answers 2

1

0 fills in for me, but florida doesn't have quotes, which is invalid JSON. To make life a little easier, instead building a here-string, consider building an object and converting it to JSON with the built-in cmdlet ConvertTo-Json.

In this example I'll show you how to do it using a hashtable

function test($test1, $test2)
{
 $details = @{ 
 "updateDetails"= 
 @(
    @{
        "customer" = "John"
        "rank" = $test1
    },
    @{
        "school" = "western"
        "address" = $test2
    }
    )
}

return $details | ConvertTo-Json
}

test 0 florida

output

{
    "updateDetails":  [
                          {
                              "customer":  "John",
                              "rank":  0
                          },
                          {
                              "school":  "western",
                              "address":  "florida"
                          }
                      ]
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your code is perfectly fine. I ran your example and it worked as expected. Maybe you missed updating the function. Close the shell and then try again.

To include "florida" as string you could simply add quotes around the variable "$test2", or even safer: Use ConvertTo-Json to output a properly quoted and escaped JSON string:

function test {
    param ([int]$rank, [string]$address)
    return @"
    { "updateDetails": [
        {
            "customer": "John",
            "rank": $rank
        },
        {
            "school": "western",
            "address": $(ConvertTo-Json $address)
        }
        ]
    }
"@
}
test 0 florida

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.