工作,我具备的功能GET_USER,搜索键入的用户名:的try/catch不是在PowerShell中
function get_user
{
$url2 = "myurl/userName:" + $userName
$contentType2 = "application/json"
$basicAuth2 = post_token
$headers2 = @{
Authorization = $basicAuth2
}
$body2 = @{
grant_type = 'client_credentials'
}
$getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2 -Headers $headers2 -Body $body2
return $getUser.userName
}
然后,我有我的主要方法try/catch语句这是不工作:
#MAIN
try {
$userName = Read-Host -Prompt "Input the user's username"
$getUser = get_user
if ($userName -eq $getUser)
{
$courseId = Read-Host -Prompt "Input the course's ID"
$availability = Read-Host -Prompt "Available? (Yes/No)"
$courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)"
$confirmationEnrollment = putStudentCourse
" "
"####################################################"
"Success!"
"####################################################"
}
else
{
$firstName = Read-Host -Prompt "First Name"
$lastName = Read-Host -Prompt "Last Name"
$netId = $userName
$email = $userName + "@school.edu"
$password = Read-Host -Prompt "Password"
$uin = Read-Host -Prompt "ID Number"
$isAvailable = Read-Host -Prompt "Available? (Yes/No)"
$confirmationUserCreate = user_create
" "
"####################################################"
"User created!"
"####################################################"
" "
$courseId = Read-Host -Prompt "Input the course's ID"
$confirmEnroll = putStudentCourse
" "
"####################################################"
"User enrolled!"
"####################################################"
}
}
catch [System.Net.HttpWebRequest]
{
"####################################################"
"User not found. We'll create it now!"
"####################################################"
" "
}
现在你键入一个不存在的用户名后抛出错误:
Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At E:\Blackboard_REST_API_Project\PowerShell\Post_Student_Course.ps1:42 char:13
+ $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
我想隐藏红色错误并输出我在catch语句中的内容,但它跳过catch并直接跳到else找不到用户名。有任何想法吗?
嗨emanresu。捕捉错误并输出catch语句中的内容,太棒了!唯一的问题是它会终止程序并且它不会转到else语句 – SPedraza
您可能正在捕捉错误的异常类型。除此之外,我不认为这个代码会做你想做的。如果get_user引发错误,那么您将跳过包含“用户创建的”文本的代码段。您是否意味着在发生错误时创建用户? – emanresu
正确。如果找到用户,请继续使用if语句(要求提供课程ID,它将注册用户,我有另一个功能)。如果没有,跳转到else语句并创建用户。 – SPedraza