修改
我正在尝试从文本文件中读取标记值,以构建可用于REST API调用的标头。
如果我使用凭证(选项T)请求临时令牌,则后续REST方法有效但如果我从本地文件系统上的文本文件(选项P)中读取永久令牌,则使用临时令牌失败。
错误:Invoke-RestMethod:底层连接已关闭:An 发送时发生意外错误。 Invoke-Test.ps1(41,13):错误:在行:41 char:13 ERROR:+ $ response = Invoke-RestMethod -Method Get -Headers $ headers -Uri" $ ap ...错误:+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~错误:+ CategoryInfo:InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest)[Invoke-RestMethod], WebException错误:+ 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 :(得分:0)
更改代码,因为powershell不会像正式编程语言那样响应运算符。
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
}