工作,我具備的功能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