【问题标题】:Powershell 2.0 Webrequest POSTPowershell 2.0 Webrequest POST
【发布时间】:2020-11-09 23:11:55
【问题描述】:

我是 Powershell 的初学者,想知道是否有人可以帮助我解决以下问题。

$baseurl = "some url address"
$Body = @{
    jsonrpc = "2.0"
    method = "user.login"
    params = @{
        user = "username"
        password = "password"
    }
    id = 1
    auth = $null
}

$BodyJSON = ConvertTo-Json $Body
write-host $BodyJSON
try {
    $zabSession = Invoke-RestMethod ("$baseurl/api_jsonrpc.php") -ContentType "application/json" -Body $BodyJSON -Method Post | `
    Select-Object jsonrpc,@{Name="session";Expression={$_.Result}},id,@{Name="URL";Expression={$baseurl}}

问题是我需要将上面的内容转换为在 powershell 2.0 中使用,因为 invoke-restmethod 不起作用。有人可以提供代码或其他东西来帮助我吗?非常感谢!

【问题讨论】:

  • Stack Overflow 不是代码编写服务。请参考文档并进行独立研究并尝试自己解决问题。
  • 正确 - 但它是一个提供帮助的平台,所以也许让我们提供支持,如果您有任何信息,请给我。此外,我已经并且仍在对此进行研究以尝试解决它,因此我在这里寻求帮助。
  • 更新问题以包含您尝试过的内容和无效的内容。

标签: .net powershell powershell-2.0 invoke


【解决方案1】:

为了在 PowerShell v2 中实现与 Invoke-RestMethod cmdlet 类似的功能,我相信您需要使用 .NET System.Net.WebRequest & System.IO.StreamWriter/StreamReader 类。这是一个模仿 Invoke-RestMethod cmdlet 基本功能的快速函数。

function InvokeRest {
  [CmdletBinding()]
  Param (
    [Parameter(Mandatory = $true, Position = 0)]
    [string]$URI,

    [Parameter(Mandatory = $true, Position = 1)]
    [string]$ContentType,

    [Parameter(Mandatory = $false, Position = 2)]
    [string]$Body,

    [Parameter(Mandatory = $false, Position = 3)]
    [ValidateSet('POST', 'GET')] #You can extend this to all the System.Net.WebRequest methods.
    [string]$Method = 'POST'
  )

  try {
    $restRequest = [System.Net.WebRequest]::Create($URI)
    $restRequest.ContentType = $ContentType
    $restRequest.Method = $Method

    if ($Method -eq 'POST') {
      $encoding = [System.Text.Encoding]::UTF8

      $restRequestStream = $restRequest.GetRequestStream()
      $restRequestWriter = New-Object System.IO.StreamWriter($restRequestStream, $encoding)
      
      $restRequestWriter.Write($Body)
    }
  }
  finally {
    if ($null -ne $restStream) { $restRequestStream.Dispose() }
    if ($null -ne $restWriter) { $restRequestWriter.Dispose() }
  }

  try {
    $restResponse = $restRequest.GetResponse()
    $restResponseStream = $restResponse.GetResponseStream()

    $responseStreamReader = New-Object System.IO.StreamReader($restResponseStream)

    $responseString = $responseStreamReader.ReadToEnd()
  }
  finally {
    if ($null -ne $restResponse) { $restResponse.Dispose() }
    if ($null -ne $restResponseStream) { $restResponseStream.Dispose() }
    if ($null -ne $responseStreamReader) { $responseStreamReader.Dispose() }
  }

  return $responseString
}

此函数将响应作为字符串返回。然后,您可以将字符串转换为适当的类型(ConvertFrom-Json/ConvertFrom-Yaml/自定义转换器)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多