将 Curl 转换为 Invoke-WebRequest

将 Curl 转换为 Invoke-WebRequest

我有下面的脚本代码,它使用 curl 进行此操作,我想使用 powershell 的 Invoke-WebRequest 复制相同的操作。怎么做。

$FX_USER=$args[0]
$FX_PWD=$args[1]
$FX_JOBID=$args[2]
$REGION=$args[3]
$FX_HOST=$args[4]

$runId=$(curl -k --header  "Content-Type: application/json;charset=UTF-8" -X POST -d '{}' -u ""${FX_USER}":"${FX_PWD}"" ""${FX_HOST}"/api/v1/runs/job/${FX_JOBID}?region=${REGION}" | jq -r '."data"|."id"')
Write-Host "runId = $runId"

答案1

$FX_USER=$args[0]
$FX_PWD=$args[1]
$FX_JOBID=$args[2]
$REGION=$args[3]
$TAGS=$args[4]
$SUITES=$args[5]
$CATEGORIES=$args[6]
$FX_HOST=$args[7]

Write-Host "user = ${FX_USER}"
Write-Host "region = ${REGION}"
Write-Host "jobid = ${FX_JOBID}"
Write-Host "hostname = ${FX_HOST}" 



$pair = "${FX_USER}:${FX_PWD}"
Write-Host "$pair"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
Write-Host "$base64"
$basicAuthValue = "Basic $base64"
Write-Host "$basicAuthValue"
$headers = @{ Authorization = $basicAuthValue }
Write-Host "$headers"

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy







$runId=$((Invoke-WebRequest  -Uri "${FX_HOST}/api/v1/runs/job/${FX_JOBID}?region=${REGION}"   -Headers $headers -Method POST  -ContentType "application/json;charset=UTF-8" ) | ConvertFrom-Json  | select -expand data | select -expand id)

Write-Host "runId = $runId"

答案2

您是否已经阅读并练习了 cmdlet,并尝试了帮助文件中的示例以完全掌握它?

# get function / cmdlet details
(Get-Command -Name Invoke-WebRequest).Parameters
Get-help -Name Invoke-WebRequest -Full
Get-help -Name Invoke-WebRequest -Online
Get-help -Name Invoke-WebRequest -Examples

您是否尝试过使用 Invoke-WebRequest 执行的操作,看看它是否成功?您遇到了什么错误。

PowerShell 使用 curl 作为 Invoke-WebRequest 的别名。它们当然不是同一个东西,因此无法完全相同地复制。

PSCore(Windows / Linux / OSX)中的 Web cmdlet 比 PSv5x 及以下版本有所改进。为确保您不会遇到站点连接问题,请务必使用...

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 

...在您的代码中。PSCore 旨在与 Windows PowerShell 并行运行,但不会取代它。

使用 cmdlet cUrl 与 Invoke-WebRequest

$headers = @{
  'X-JFrog-Art-Api' = $apiKey
  "Content-Type" = "application/json"
  "Accept" = "application/json"
}
Invoke-WebRequest -InFile $file -Method Put -Uri "$ARTIFACTORY_HOST/third-party/test/readme.md" -Headers $headers -Verbose


curl -T readme.md "${ARTIFACTORY_HOST}/third-party/test/readme.md " \
-H "X-JFrog-Art-Api: ${apiKey}" \
-H "Content-Type: application/json" \
-H "Accept: application/json"

您也可以直接在 PowerShell 中使用 curl.exe,如果您选择这样做,就像使用任何其他外部 exe 一样。

相关内容