4

I have an issue I can't figure out. It is a syntax problem that can't solve. Let's say I have this function:

function putStudentCourse ($userName, $courseId)
{           
    $url = "http://myurl/learn/api/public/v1/courses/courseId:" + $courseId + "/users/userName:" + $userName

    $contentType = "application/json"       
    $basicAuth = post_token
    $headers = @{
              Authorization = $basicAuth
             }
    $body = @{
              grant_type = 'client_credentials'
             }
    $data = @{
            courseId = $courseId
            availability = @{
                available = 'Yes'
                }
            courseRoleId = 'Student'
        }
    $json = $data | ConvertTo-Json

    $putStudent = Invoke-RestMethod -Method Put -Uri $url -ContentType $contentType -Headers $headers -Body $json

    return $json
}

And then my main method:

#MAIN

$userName = "user02";
$courseId = "CourseTest101"

$output =  putStudentCourse($userName, $courseId)
Write-Output $output

Right now it is just returning the first vale ($userName) but the output shows like this:

{
    "availability":  {
                         "available":  "Yes"
                     },
    "courseRoleId":  "Student",
    "courseId":  null
}

Somehow $courseId is never filled and I am not sure why. What am I doing wrong? Any help will be appreciated it.

SPedraza
  • 159
  • 2
  • 2
  • 10
  • Additional note: if you [use strict mode](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/set-strictmode), it will catch this incorrect function call usage. – briantist Apr 25 '17 at 18:35

1 Answers1

15

It's a syntax issue. When defining a function, you put the parameters in parenthesis as you correctly did here:

function putStudentCourse ($userName, $courseId)

But when you invoke a function, you do not put the arguments in parenthesis. Change your code to read like this:

$output =  putStudentCourse $userName $courseId

The powershell interpreter interprets the original code

$output =  putStudentCourse($userName, $courseId)

To mean, "create a list of ($userName, $courseId), and pass that as the first parameter to putStudentCourse."

Jeffrey Rennie
  • 3,193
  • 1
  • 18
  • 19