2017-04-25 127 views
0

我有個問題,我找不出來。這是一個無法解決的語法問題。比方說,我有這樣的功能:將多個參數傳遞給Powershell中的函數變量

function putStudentCourse ($userName, $courseId) 
{   
    $url = "http://myurl/learn/api/public/v1/courses/courseId:" + $courseId + "https://stackoverflow.com/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 
} 

然後我的主要方法:

#MAIN 

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

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

現在它只是返回第一淡水河谷($用戶名),但輸出這樣表示:

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

不知何故$ courseId是從來沒有填充,我不知道爲什麼。我究竟做錯了什麼? 任何幫助將不勝感激。

+0

附加說明:如果您[使用嚴格模式(https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/set-strictmode),它會抓住這個不正確函數調用使用。 – briantist

回答

3

這是一個語法問題。當定義一個函數,你把參數在括號中爲你正確地在這裏做:

function putStudentCourse ($userName, $courseId) 

但是,當你調用一個功能,你將這些參數在括號中。改變你的代碼讀取這樣的:

$output = putStudentCourse $userName $courseId 

PowerShell的解釋程序的原代碼

$output = putStudentCourse($userName, $courseId) 

的意思,「創建($用戶名,$ courseId)的列表,並傳遞作爲第一個參數putStudentCourse「。

+0

非常感謝,那是它! – SPedraza

相關問題