將 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 的別名。它們當然不是同一件事,因此不能完全相同地複製。

Web cmdlet 比 PSv5x 及更低版本中的 PSCore (Windows / Linux / OSX) 進行了改進。為了確保您不會遇到網站連線問題,請確保使用...

[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 一樣。

相關內容