将多个参数传递给Powershell中的函数变量[重复]
Posted
技术标签:
【中文标题】将多个参数传递给Powershell中的函数变量[重复]【英文标题】:Passing multiple parameters to function variables in Powershell [duplicate] 【发布时间】:2017-09-22 22:00:15 【问题描述】:我有一个无法解决的问题。这是一个无法解决的语法问题。假设我有这个功能:
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
然后是我的主要方法:
#MAIN
$userName = "user02";
$courseId = "CourseTest101"
$output = putStudentCourse($userName, $courseId)
Write-Output $output
现在它只是返回第一个值 ($userName) 但输出显示如下:
"availability":
"available": "Yes"
,
"courseRoleId": "Student",
"courseId": null
不知何故 $courseId 从未被填满,我不知道为什么。我究竟做错了什么? 任何帮助将不胜感激。
【问题讨论】:
补充说明:如果你use strict mode,它会捕捉到这个不正确的函数调用用法。 【参考方案1】:这是一个语法问题。定义函数时,将参数放在括号中,就像您在此处所做的那样:
function putStudentCourse ($userName, $courseId)
但是当您调用一个函数时,您确实不将参数放在括号中。将您的代码更改为如下所示:
$output = putStudentCourse $userName $courseId
powershell解释器解释原始代码
$output = putStudentCourse($userName, $courseId)
意思是“创建一个 ($userName, $courseId) 列表,并将其作为第一个参数传递给 putStudentCourse。”
【讨论】:
非常感谢,成功了!以上是关于将多个参数传递给Powershell中的函数变量[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何将多个(非单元)参数传递给 Octave 的 parcellfun() 中的函数?