Uploading to Artifactory from a Windows Powershell script Uploading to Artifactory from a Windows Powershell script powershell powershell

Uploading to Artifactory from a Windows Powershell script


I tried the Invoke-WebRequest option and was able to get this to work:

$URI = New-Object System.Uri("https://artifactory.example.com/artifactory/net-generic-local/APP/BF_2.0.zip")  $SOURCE = ".\BF_2.0.zip"  $AF_USER = "user"  $AF_PWD = ConvertTo-SecureString "password" -AsPlainText -Force  $CREDS = New-Object System.Management.Automation.PSCredential ($AF_USER, $AF_PWD)  Invoke-WebRequest -Uri $URI -InFile $SOURCE -Method Put -Credential $CREDS  

Had to create a PSCrendential object so it would not prompt for the user password. But other then that, this work exactly as I needed.


The reason for your issue is HTTP method used by UploadFile.By default UploadFile uses POST, while to upload file to Artifactory you need to use PUT method. That is why you get 405 "Method Not Allowed" response.

To fix this use UploadFile overload with three parameters like shown here:https://msdn.microsoft.com/en-us/library/ms144230(v=vs.110).aspx

So the correct version of the code will look like:

$SOURCE = ".\BF_2.0.zip"  $DESTINATION = "https://artifactory.example.com/artifactory/net-generic-local/APP/BF_2.0.zip"  $AF_USER ="user"  $AF_PWD ="password"  $WebClient = New-Object System.Net.WebClient  $WebClient.Credentials = New-Object System.Net.NetworkCredential($AF_USER, $AF_PWD)  $URI = New-Object System.Uri($DESTINATION)$METHOD = "PUT"  $WebClient.UploadFile($URI, $METHOD, $SOURCE)  


I don't have Artifactory handy, but you might want to try the Invoke-RestMethod PowerShell cmdlet, available in box from PowerShell v3 and higher. Here's a sample of how to do that.

You'll need credentials, and based on their REST documentation, basic authentication of the type we can get with the -Credential param of Invoke-RestMethod should cover us there.

You'll also need to provide a message $body with your request. Look at the JSON sample here from their docs, and then edit the $body I've given as a starting point.

$credential = Get-Credential$body = @{action="Upload";param2="Data";param3="Data";} | ConvertTo-Json Invoke-RestMethod -uri "http://localhost:8080/artifactory/api/build" `  -ContentType "application/json" -method POST -body $body -Credential

I must say, this is one of the more complex examples of a REST API that I've seen, so to make this easier, I would install curl on a machine and use Fiddler to capture a trace successfully uploading a file. To make things even easier, you could also do this using the Artifactory UI from a browser to upload a file, and simple record a trace of the upload step. Then, grab the JSON in the request and use that as a starting point.