Recently, I encountered a task that required calling our IL REST API method using PowerShell to automate the process of account updates. The goal was to have a PowerShell script that reads a file containing pairs of account names and account notes and subsequently calls the IL method for each account.
Initially straightforward, I encountered a logging issue that proved challenging. Thankfully, with assistance from ChatGPT, I resolved the problem and successfully prepared the script.
Here’s the script’s skeleton for future reference:
$uri = 'http://localhost:8016/Account/whatever' $username = "username" $password = "password" $pair = "{0}:{1}" -f ($username, $password) $bytes = [System.Text.Encoding]::ASCII.GetBytes($pair) $token = [System.Convert]::ToBase64String($bytes) $headers = @{ Authorization = "Basic {0}" -f ($token) } $inputFilePath = 'c:\temp\accounts.txt' Get-Content -Path $inputFilePath | ForEach-Object { $accountName = $_.Trim() $customNote = [PSCustomObject]@{ Text = "CHANGE ME!" Level = 2 } $notesList = New-Object System.Collections.ArrayList $notesList.Add($customNote) $requestObject = [PSCustomObject]@{ accountName = $accountName notes = $notesList } $jsonBody = $requestObject | ConvertTo-Json Invoke-RestMethod -uri $uri -Method POST -ContentType "application/json" -Body $jsonBody -Headers $headers }
Note: Basic authentication, as commonly seen in examples, didn’t work for me. Hence, I manually prepared headers containing the authorization token. With this adjustment, the script now functions correctly.
Standard examples from the Internet:
$username = "username" $password = "password" $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $credentials = New-Object System.Management.Automation.PSCredential($username, $secpasswd) Invoke-RestMethod -Uri $uri -Method Post -Body $jsonBody -ContentType "application/json" -Credential $credentials
What works for me:
$username = "username" $password = "password" $pair = "{0}:{1}" -f ($username, $password) $bytes = [System.Text.Encoding]::ASCII.GetBytes($pair) $token = [System.Convert]::ToBase64String($bytes) $headers = @{ Authorization = "Basic {0}" -f ($token) } Invoke-RestMethod -Uri $uri -Method Post -Body $jsonBody -ContentType "application/json" -Headers $headers
If you wish to send explicitly declared JSON (not the object serialized to JSON), you can use the following format:
$jsonBody = @" { "accountName": "12720", "notes": [ { "text": "CHANGE ME!", "level": 2 } ] } "@
Additionally, if you desire to display the serialized response, add the following line:
$response | ConvertTo-Json
I hope this proves beneficial for you in the future, Future Paweł! 🙂