0
votes

I am trying to execute REST API within powershell using invoke-restmethod/invoke-webrequest but failed when I pass Json inputs. It works with CURL command.

curl -v --user admin:password -H Accept:application/json -H Content-Type:application/json -d "@C:\data\test.json" -X POST http://10.11.60.88:8081/artifactory/api/distribute

Test.json contents are as below

{

"targetRepo" : "ECSDigital_Bintray", 
"packagesRepoPaths" : ["SNOW/org/apache/maven/maven-artifact/3.3.9/maven-artifact-3.3.9.jar"] 

}

I am writting below powershell and it gives me series of errors.

$user = "admin"

$pass = "password"

$secpasswd = ConvertTo-SecureString $user -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential ($pass, $secpasswd)

$postParams = @{targetRepo='SNOW';packagesRepoPaths='["org/apache/maven/maven-artifact/3.3.9/maven-artifact-3.3.9.jar"]'}

Invoke-WebRequest -Uri "http://10.11.60.88:8081/artifactory/api/distribute" -Credential $cred -Method Post -ContentType "application/json" -Body $postParams

Error: Invoke-WebRequest : The remote server returned an error: (400) Bad Request.

I have tried some combinations of json inputs but no go. Any help?

1

1 Answers

0
votes

I have fixed the issue, the following way solved my issues, there was need of additional ""

$params = @{

uri = $ARTIFACTORY_PROTOCOL+"://"+$ARTIFACTORY_IP+":"+$ARTIFACTORY_PORT+"/artifactory/api/distribute";

Method = 'POST';

Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($ARTIFACTORY_USERNAME):$($ARTIFACTORY_PASSWORD)"));"Accept" = 'application/json';"Content-Type" = 'application/json'}

#body = @{""targetRepo"" : ""$DISTRIBUTION_REPOSITORY"", ""packagesRepoPaths"" : ""$ARTIFACTORY_PATH""} 

}

$json = "{
           ""targetRepo"":""$DISTRIBUTION_REPOSITORY"",
           ""packagesRepoPaths"":[""$ARTIFACTORY_PATH""]
         }"

$var = invoke-restmethod @params -Body $json
echo $var