PowerShell API Examples¶
These examples call the KnowledgeLake API from PowerShell with Invoke-RestMethod. Copy the helper once, then use the task you need.
At a glance
- Tool PowerShell 7 or later (the JSON calls also run in Windows PowerShell 5.1)
- Tasks on this page Test a token, get a work item, upsert metadata, run a saved search, create a work item and send it to a workflow, list failed jobs
- Token features used Manage Work Items, Manage Workflows, Run Searches, Query Jobs
- Pattern One helper does every JSON call, checks
Success, and fails withMessageKeyorMessages[].MessageKey
For the call shape, the token header and the response envelope, see the Introduction. For every work item action, see the KWorkItem API reference.
Setup¶
- PowerShell 7 or later (the file upload uses
-Form). The JSON calls also work in Windows PowerShell 5.1. - A token in the user environment variable
KnowledgeLakeApiToken. Never write the token into a script file.
$KLBase = "https://yourcompany.knowledgelake.io/api"
$KLHeaders = @{ TempIdentityToken = $env:KnowledgeLakeApiToken }
# POST one action with a JSON body. Return Data, or throw with the API's message text.
function Invoke-KL {
param([string]$Action, [object]$Body = @{})
try {
$r = Invoke-RestMethod -Method Post -Uri "$KLBase/$Action" -Headers $KLHeaders `
-ContentType "application/json" -Body ($Body | ConvertTo-Json -Depth 10)
}
catch {
# HTTP 401, 412, 422 and 500 land here. The envelope is in ErrorDetails.
$detail = $_.ErrorDetails.Message
try {
$env = $detail | ConvertFrom-Json
if ($env.Messages) { $detail = ($env.Messages | ForEach-Object { $_.MessageKey }) -join "; " }
elseif ($env.MessageKey) { $detail = $env.MessageKey }
} catch { }
throw "$Action failed: $detail"
}
if (-not $r.Success) { throw "$Action failed: $($r.MessageKey)" }
return $r.Data
}
The text of an error is in MessageKey (or Messages[].MessageKey). There is no Message property.
Test the token¶
An error with User Is Unauthorized means the token is wrong or lacks Manage Workflows.
Get a work item¶
$workItemId = "<work item guid>"
$wi = Invoke-KL "V1_KWorkItemAPI/GetWorkItem" @{ WorkItemId = $workItemId }
"Work item: $($wi.Name)"
$wi.Documents | ForEach-Object { "{0} {1}" -f $_.Id, $_.Metadata.Index.Title }
Invoke-KL returns Data, so the documents are $wi.Documents. A document's id is Id.
Upsert metadata¶
# Work item level (routes read these values)
Invoke-KL "V1_KWorkItemAPI/UpsertWorkItemMetadata" @{
WorkItemId = $workItemId
Metadata = @(
@{ Bucket = "Index"; Key = "NeedsReview"; Value = "Yes" }
)
} | Out-Null
# One document
Invoke-KL "V1_KWorkItemAPI/UpsertDocumentMetadata" @{
WorkItemId = $workItemId
DocumentId = $wi.Documents[0].Id
Metadata = @(
@{ Bucket = "Index"; Key = "ApprovalStatus"; Value = "Approved" },
@{ Bucket = "General"; Key = "EditedBy"; Value = "powershell" }
)
} | Out-Null
Every value is a string: send "true" and "1250.00", not $true and 1250.
Run a saved search¶
$searches = Invoke-KL "V1_RepositoryAPI/GetSavedSearches" @{}
$search = $searches | Where-Object { $_.SavedSearchName -eq "Invoices by Vendor" } | Select-Object -First 1
$cond = $search.SearchConditions | Where-Object { $_.ParameterInternalName -eq "VendorName" } | Select-Object -First 1
$strings = @{}
$strings[$cond.ConditionId] = "Gateway Fleet Services LLC"
$result = Invoke-KL "V1_RepositoryAPI/RunSavedSearch" @{
SearchId = $search.SavedSearchId
SearchCatalogId = $search.SearchCatalogId
StartRow = 0
RowLimit = 200
SearchConditions = @{ Strings = $strings }
}
$result.Results | ForEach-Object { $_.ResultItemId }
Page with StartRow until a page has fewer rows than RowLimit. See Run a saved search.
Create a work item and send it to a workflow¶
$filePath = "C:\invoices\Invoice_20481.pdf"
$workflowName = "Invoice Approval"
# 1. Create the work item.
$new = Invoke-KL "V1_KWorkItemAPI/NewWorkItem" @{
WorkItemName = [IO.Path]::GetFileNameWithoutExtension($filePath)
Metadata = @( @{ Bucket = "General"; Key = "Source"; Value = "powershell" } )
}
$newId = $new.WorkItemId
# 2. Add the file (multipart/form-data). MetadataParameter is a JSON string.
$docMetadata = @{ Metadata = @( @{ Bucket = "Index"; Key = "InvoiceNumber"; Value = "20481" } ) } | ConvertTo-Json -Depth 5
$added = Invoke-RestMethod -Method Post -Uri "$KLBase/V1_KWorkItemAPI/AddDocument" -Headers $KLHeaders -Form @{
WorkItemId = $newId
File = Get-Item $filePath
MetadataParameter = $docMetadata
}
if (-not $added.Success) { throw "AddDocument failed: $($added.MessageKey)" }
# 3. Start the workflow.
$workflow = Invoke-KL "V1_WorkflowAPI/GetAllWorkflows" | Where-Object { $_.WorkflowName -eq $workflowName } | Select-Object -First 1
Invoke-KL "V1_WorkflowAPI/SendToWorkflow" @{ WorkflowId = $workflow.WorkflowId; WorkItemId = $newId } | Out-Null
"Created $newId and sent it to $workflowName"
Add every document before SendToWorkflow. See Create a work item and send it to a workflow for the full list of checks.
List failed jobs¶
Invoke-KL "V1_JobsAPI/QueryForJobRuns" @{ JobStatus = "Error"; PageSize = 200 } |
Select-Object JobDisplayName, JobID, LastRuntime
# Rerun one after you checked it (needs Manage Jobs):
# Invoke-KL "V1_JobsAPI/ResubmitJob" @{ JobInstanceID = "<JobID>" } | Out-Null
For a full watchdog with history, RPA tasks and safe retries, see Find and resubmit failed jobs.
What can go wrong¶
| What you see | Cause and fix |
|---|---|
| Nested metadata arrays turn into strings | ConvertTo-Json stops at depth 2 by default. Pass -Depth 10, as Invoke-KL does. |
User Is Unauthorized on endpoint ... |
The token lacks the feature for that action. See Authentication. |
-Form is not recognized |
You run Windows PowerShell 5.1. Use PowerShell 7 for the upload. |
$true sent as a value |
Every metadata value is a string. Send "true". |