Shell script example
PowerShell Script Example (.ps1)
# Set variables
$PROTOCOL = "https"
$BASE_URL = "example.app.bearingx.io" # Insert your own BEARING X URL
$USERNAME = "exampleUserBEARINGX" # Insert your own username
$PASSWORD = "examplePasswordBEARINGX" # Insert your own password
$FILENAME = "C:\Users\DeniseHaddad\Desktop\BX Upload\BEARING X - CSV-Testliste-kurz.csv" # Insert your own path to the CSV file
$WORKDIR = ".\"
$COOKIE_FILE = "$WORKDIR\bearingx_cookie.txt"
# Function for error handling
function Handle-Error {
Write-Host "Fehler beim Upload." -ForegroundColor Red
if ($Error[0]) {
Write-Host "Fehlerdetails: $($Error[0])" -ForegroundColor Yellow
}
exit 1
}
# Change to the working directory
Write-Host "Starting automatic upload..."
try {
Set-Location -Path $WORKDIR -ErrorAction Stop
} catch {
Write-Host "Arbeitsverzeichnis konnte nicht gesetzt werden." -ForegroundColor Red
Handle-Error
}
# Log in and save cookies
Write-Host "Logging in as '$USERNAME' and saving cookie..."
try {
$loginResponse = Invoke-WebRequest -Uri "${PROTOCOL}://${BASE_URL}/login" `
-Method POST `
-Body @{username=$USERNAME; password=$PASSWORD} `
-ContentType "application/x-www-form-urlencoded" `
-SessionVariable Session
Write-Host "Login erfolgreich!" -ForegroundColor Green
} catch {
Write-Host "Login fehlgeschlagen!" -ForegroundColor Red
Handle-Error
}
# Upload file manually
Write-Host "Uploading file '$FILENAME'..."
try {
# Read the contents of the file
$fileBytes = [System.IO.File]::ReadAllBytes($FILENAME)
$boundary = "----WebKitFormBoundary$(Get-Random)"
# Create multi-part form data
$body = "--$boundary`r`n" +
"Content-Disposition: form-data; name=`"file`"; filename=`"$(Split-Path $FILENAME -Leaf)`"`r`n" +
"Content-Type: text/csv`r`n`r`n" +
([System.Text.Encoding]::UTF8.GetString($fileBytes)) + "`r`n" +
"--$boundary--"
$headers = @{
"Content-Type" = "multipart/form-data; boundary=$boundary"
}
# Send the request
$uploadResponse = Invoke-WebRequest -Uri "${PROTOCOL}://${BASE_URL}/api/orders/upload" `
-Method POST `
-Body $body `
-Headers $headers `
-WebSession $Session `
-ErrorAction Stop
Write-Host "Upload erfolgreich! Status: $($uploadResponse.StatusCode)" -ForegroundColor Green
} catch {
Write-Host "Upload fehlgeschlagen!" -ForegroundColor Red
Handle-Error
}
Write-Host "Process completed."
exit 0
How does the script work?
The following description is based on the script shown above. The script is only an example of how an upload is possible.
To run the script, PowerShell ISE must be opened as an administrator (it is best to enter this in the Windows search and then right-click to open as an administrator). Then insert the script shown above. The lines with the URL, the user name, the password and the file path must be adapted (purple colored lines). Finally, simply execute the script (green play button).