Wednesday, October 24, 2018

OAC - PowerShell RestAPI to Upload files from On-Prem to OAC

Today, we are going to see a function which uploads files / data from your On-Prem Server to OAC.

Read my prior blog so that you get the basics on authenticating to OAC and getting the Object handle to invoke the rest commands.

Pre-requisites:

- Create a folder on your local server - D:\Up
- Create a file "MyUploadFile.txt"  within the folder created above. You can create any number of files. 
- Ensure you are running the PowerShell version 4 or above.

Without delay, I'll straight away introduce the code (which has explicit comments on each step to understand it better).

PowerShell Code:

Function UploadingFiles {  

#Parameters passed to the above function
param( [string] $dirToUpload, [string] $upURL )

# This Steps constructs your Rest API Base URL
$baseURL = "http://<your OAC URL>/essbase/rest/v1/" 

#Logging in to OAC - Replace the $username and $password with your specifics.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 
$EncodedAuthorization = [System.Text.Encoding]::UTF8.GetBytes("<username>" + ":" + "<password>") 
$EncodedPassword = [System.Convert]::ToBase64String($EncodedAuthorization) 
$headers = @{"Authorization"="Basic $($EncodedPassword)"} 

# Construct your upload URL
$uploadURL = $baseURL + $upURL

# Files in the folder which needs to be uploaded
$filesTobeUploaded = Get-ChildItem $dirToUpload 

# Loop through the folder and upload the files to OAC
ForEach($file in $filesTobeUploaded) { 
     $restURL = $uploadURL + $file 
     $restResponse = Invoke-RestMethod -Uri $restURL -Method Put -Header $headers -ContentType "application/octet-stream" -OutFile "$file" 



Use the below command to call the function written above

#Function Call
UploadingFiles -dirToUpload "D:\Up\" -upURL "files/shared/" 

Please try this out and provide your feedback on the comments section.

No comments:

Post a Comment