2017-06-21 2 views
1

EDIT:変更認証フローとなりまし受けERROR:基になる接続が閉じられました:起動-RestMethodは、予期しないエラーが送信時に発生した

私が構築するために、テキストファイルからのトークン値を読み込むしようとしていますREST API呼び出しに使用できるヘッダー。

資格情報(オプションT)を使用して一時的なトークンを要求すると、後続のRESTメソッドが機能しますが、ローカルファイルシステムのテキストファイル(オプションP)から固定トークンを読み込むと、トークンは失敗します。

ERROR: Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send. Invoke-Test.ps1 (41, 13): ERROR: At Line: 41 char: 13 ERROR: + $response = Invoke-RestMethod -Method Get -Headers $headers -Uri "$ap ... ERROR: +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ERROR: + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException ERROR: + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

コード:

# Allow the use of self-signed SSL certificates, TLS 
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True } 
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 

$server = "https://192.168.1.1" 
$app_rest = "$server/api/v1" 

$choice = Read-Host "Enter T or P" 
If($choice -eq "T") { 
    Write-Host "Try and obtain temp token" 
    $Username = Read-Host "Enter Username" 
    $Password = Read-Host "Enter Password" -AsSecureString 
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) 
    $Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 

      $creds = @{ 
      username = $Username 
      password = $Password 
      grant_type = "password" 
      }; 
    $response = Invoke-RestMethod -Method Post -Uri "$server/api/token" -Body $creds 
    $token = $response.access_token 
    Write-Host $token 
} 
ElseIf($choice = "P") { 
    Write-Host "Try and use perm token" 
    #$token = [IO.File]::ReadAllText("C:\temp\SBXtoken.txt") 
    $token = Get-Content "C:\temp\SBXtoken.txt" -Raw 
    Write-Host $token 
} 
Else {Break;} 

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" 
$headers.Add("Authorization", "Bearer $token") 

$response = Invoke-RestMethod -Method Get -Headers $headers -Uri "$app_rest/status" 
$status = $response.status; 
Write-Host $status 
+0

。もし私が常にIf文からそれらの行を取り除いて最初のirmを実行し、常にそれらを実行すれば、その後のすべてのirmが機能します。 – dross

答えて

0
  1. は、PowerShellは、正式なプログラミング言語と同じオペレータに応答しないため
  2. はあなたのコードを変更するには、管理者として実行していることを確認してください。ここでは、完全な喪失で

    ElseIf($choice -eq "P") { 
        Write-Host "Try and use perm token" 
        #$token = [IO.File]::ReadAllText("C:\temp\SBXtoken.txt") 
        $token = Get-Content "C:\temp\SBXtoken.txt" -Raw 
        Write-Host $token 
    } 
    
関連する問題