Zoomed Image

AMSX - The xAssets Scripting Language

AMSX is the server-side scripting language at the heart of the xAssets transformation engine. It provides direct access to the xAssets data model, API, SQL engine, HTTP services, file operations, and much more, enabling powerful integrations, automations and data processing workflows without needing to write or host external applications.

Transformations written in AMSX can be triggered from schedules, menu items, record save events, or externally via the xAssets REST API.

Command Reference

Click any command to view its full documentation, parameters and syntax.

AddColumnsToTable
Add one or more columns to a table if they do not already exist
AddCredentialPackFields
Enrich credential pack XML records with decoded metadata fields
AddCustomField
Add a custom specification field to a table if it does not already exist
AddSqlTemplate
Register a named SQL template for later use
ApplyDataMapping
Apply a data mapping lookup to update a field in a temporary table
ApplyDataMappingLike
Apply a data mapping to a table using LIKE pattern matching
ApplyDataMappingLike2
Apply a data mapping to a table using trailing LIKE pattern matching
ApplySurroundText
Wrap the result buffer with prefix and suffix text
Backup
Backup
Base64
Encode username:password credentials to Base64 for HTTP Basic Authentication
Base64Encode
Encode a string as a Base64 URL-safe value using a specified character encoding
Base64Encode2
Encode a string as a standard Base64 string
BatchSql
Execute a batch of SQL commands wrapped in the standard SQL wrapper
BeginTransaction
New transaction
BeginTransactionDateTime
Get transaction start date
BuildUrl
Construct a URL from a base address and a set of query-string parameters
CacheKill
Empty Cache
CacheRemove
Remove a named item from the server cache
CacheRemoveTable
Remove all cache entries associated with a named table
Calculate
Evaluate a mathematical or logical expression
CalculateDepreciation
Run the depreciation calculation batch via SaveSpecial
CalculateNumber
Evaluate a numeric expression and return the numeric result
CalculatePage
Calculate the total number of pages for a paged result set
CalculateResult
Evaluate the formula currently stored in the result buffer
CalculateSoftware
Run the SAM software licensing calculation engine
Call
Call an AMSX script file in an isolated scope
CallLocal
Call a local AMSX script file, sharing variables and result buffer
CDate
Parse a string and convert it to an xAssets date
CDateUS
Parse a string and convert it to a date using US date format
CheckAssetValue
Assert that the calculated value of an asset matches an expected figure
CleanColumns
Apply a cleaning operation to specified columns in a table
CleanCSVString
Remove empty items from a comma-separated string
CleanDelimitedFields
Clean delimited fields
CleanSerialNumber
Clean a single serial number value using a cleaning algorithm
CleanSerialNumberTable
Apply serial number cleaning algorithm to an entire table column
CleanUserIDToName
Clean UserID to name
ClearParams
Clear the script parameter collection
ClearText
Discard the SQL collected between TEXT and ENDTEXT without executing it
ClearTransformResult
Clear the transform's captured return value
ClearXML
Clear the AMSX XML buffer
ClosePeriod
Close an accounting period so no further depreciation changes are allowed
Code
Mark the start of a code block (processed in header)
CommandProcessor
Invoke an xAssets API command directly
Commit
Commit
CommitBegin
Commit and begin transaction
CommitSleepBegin
Commit the current transaction, pause for a short time, then begin a new one
CommitSleepMode
Configure automatic commit-and-sleep behaviour for long-running transactions
Compress
Compress a file or folder into a zip archive
ConsolidateTable
Consolidate a table by grouping rows on key fields with an aggregate function
Context
Set the context label used in error messages and the log
CopyFile
Copy a file from one path to another
CopyFiles
Copy multiple files from one folder to another
CopyFileTouch
Copy a file and update the target file's timestamp
CopyFolder
Copy a folder and its contents to a new location
CountNodes
Count child nodes
CreateDirectory
Create a directory if it does not already exist
CreateGuid
Create a GUID
CreateHierarchyTempTable
Build a temp table containing all descendants of an entity in a hierarchy
CreateTableCopy
Create a copy of a database table, optionally seeded with rows
CurrentXMLDocument
Store the current AMSX XML document in a variable
Data
Manage the output data island used to pass structured data to the browser
Data.Add
Add a named data item to the data island
Data.AddVariable
Add a single AMSX variable to the data island
Data.AddVariables
Add all currently defined AMSX variables to the data island
Data.AddXml
Add an XML data item to the data island using inline XML
Data.Xml
Add XML data to the data island from the current XML document
DatasetFileToTable
Load a binary dataset file from disk and create temporary tables from its contents
DatasetToTable
Load the in-memory dataset buffer into temporary tables
DatasetToXML
Convert dataset to XML
DatasetValue
Get a value from the dataset
DataSource
Set an XML data source for an xAssets form from the current document
DataSourceFromUrl
Set an xAssets form data source by parsing a URL string
DBStringClean
Clean a string value in a database field
Decompress
Decompress a zip archive to a folder or file
DecryptTextStrong
Decrypt a string produced by EncryptTextStrong
DeleteAPIToken
Delete an API authentication token
DeleteCredentialPack
Delete one or more credential packs from the application or collection servers
DeleteFile
Delete a file from the file system
DeleteOldFiles
Delete files older than a specified number of days from a folder
DeleteRecord
Delete one or more records from a metadata table
Depreciate
Calculate asset depreciation up to a specified date for an accounting period set
DisableTriggers
Disable triggers
DocumentObjectToClient
Send a stored binary document to the client browser for download
DocumentObjectToServer
Save a stored binary document to the server file system
DoubleSingleQuotes
Double single quotes
DownloadFile
Download a file from a URL and save it to a local path
DownloadFileSecure
Download a file from an authenticated URL and save it to a local path
DropTempTable
Drop a temporary database table if it exists
EditRecord
Edit an existing record in a metadata table
Else
Else
EmailToTable
Download emails from a mail server into a temporary table
EmitSqlToFiles
Write SQL query results to files in a folder, one file per row
EmptyFolder
Delete all files from a folder, optionally including subfolders
EnableTriggers
Enable triggers
EncryptTextStrong
Encrypt a string using strong double-clickable encoding
EndCode
Mark the end of a code block (processed in header)
EndText
Mark the end of a text block (processed in header)
Escape
Escape single quotes
ExecuteCode
Compile and execute dynamically assembled VB.NET code
ExecuteGeneratedSql
Execute SQL statements produced by the collected TEXT/ENDTEXT SQL query
ExecuteSql
Execute a SQL statement immediately
ExecuteSqlTemplate
Execute a named SQL template with positional argument substitution
ExecuteText
Execute the SQL collected in the current TEXT/ENDTEXT block
ExecuteTextBatch
Execute the collected SQL on a dedicated batch-processor connection
ExecuteTextColl
Run sql on the collection server
ExecuteTextToDataset
Execute collected SQL and store the result as a dataset, optionally writing it to a file
ExecuteTextToTable
Execute collected SQL and bulk insert, update, or delete the results into a table
ExecuteTextValue
Execute sql and store the result
ExecuteTextXML
Execute sql and load the XML
ExecuteTransactionDifference
Compare TEXT/ENDTEXT SQL output to an existing table and write difference rows as transactions
Exists
Run a SQL statement and return 1 if a value was found, or 0 if no record exists
ExpandVariables
Expand AMSX variable references in the result buffer
ExpectError
Configure error-expectation mode used in testing scripts
Fieldlist
Get the field list for a metadata table
FieldListFromURL
Extract the field names from a URL query string
FieldlistUpdateable
Get the updateable field list for a metadata table
FileExists
Check whether a file exists and store True or False in the result buffer
FileToTempTable
Load a file into a temporary database table
FileToTempTable2
Load a file into a temporary table using extended permitted folders
FindStringFromMarkers
Extract a value from a string using search and boundary markers
FixUserPermissions
Recalculate and apply the correct permissions for a user account
FlattenXML
Flatten the AMSX XML document into a single-level structure
FlattenXMLDeep
Deep-flatten the AMSX XML document into a single-level structure
FolderExists
Check whether a folder exists and store True or False in the result buffer
Form.AddField
Add an input field to the active AMSX form
Form.Create
Initialise a new AMSX form object ready to receive fields and be displayed
Form.GetData
Retrieve the value a user entered for a field after the form was submitted
Form.SetButtons
Define the action buttons shown on the active AMSX form
Form.Show
Display the active AMSX form to the calling user and suspend script execution until the form is submitted
Form.User
Target an AMSX form to a specific user's browser session
FormatDate
Format a date variable to a string using a named format
FormatDateString
Parse a date string and format it to a different string representation
FtpGet
Download a file from an FTP server to the local file system
FtpSend
Upload a file to an FTP server
GeneratePassword
Generate a secure random password for the current user
GenerateRandomString
Generate a cryptographically random alphanumeric string of a given length
GenerateUniqueString
Generate a deterministic unique string from a seed value
GenerateWorkOrders
Generate scheduled work orders for maintenance tasks
GetAssetValue
Calculate the financial value of an asset and store it in the result buffer
GetCode
Copy the Code block content into the result buffer
GetCodeEval
Copy the Code block into the result buffer with variable substitution
GetComputersOnline
Load the list of currently online computers into a temporary table
GetFileName
Extract the file name portion from a full file path
GetFilePath
Extract the directory portion from a full file path
GetFilePathWeb
Extract the directory or base path from a file path or web URL
GetLicenseXML
Load the xAssets license XML into the current document
GetNode
Read the inner text of the currently selected XML node
GetParameter
Look up a named value from a parallel field-list and value-list
GetText
Copy the raw Text block content into the result buffer
GetVariable
Read a variable's raw value into the result buffer, bypassing command parsing
HexToString
Convert a Unicode hex string back to a plain string
HttpGet
Send an HTTP GET request and store the response in the result buffer
HttpGetNet
Send an HTTP GET request using the .NET HTTP stack with full credential and header support
HttpHeader
Add a custom HTTP header for the next HttpGetNet or HttpSendNet call
HttpSend
Send an HTTP POST or PUT request and store the response in the result buffer
HttpSendNet
Send an HTTP POST or PUT request using the .NET HTTP stack with full credential and header support
HttpSendNetResult
POST the current result buffer as the body of an HTTP request
HTTPSendNetTimeout
Set the timeout for the next HttpGetNet or HttpSendNet call
HttpSendNetXML
POST the current AMSX XML buffer to an HTTP endpoint
HttpStatus
Get HTTP status description
HttpStatusCode
Get HTTP status
HttpStatusError
Retrieve the error message from the last HTTP operation
Instr
Find the position of a substring within a string
IntegerDivide
Divide two integers and return the integer quotient
IsXML
Test whether a value is valid XML
JoinThreads
Join threads
JsonSelect
Query the active AMSX JSON object using a JSONPath selector expression
JsonSet
Set a property or array element in the active AMSX JSON object
JsonToResult
Serialise the active AMSX JSON object to a string and store it in the result buffer
JsonToXML
Convert raw JSON to an XML document using Newtonsoft
JsonToXML2
Convert JSON in the result buffer to an XML document using the internal JSONParser
JsonToXMLTable
Convert a JSON string to XML using explicit record and field path mappings
JsonValue
Read a single value from the active AMSX JSON object by key
JsonWebToken
Create a signed JSON Web Token and store it in the result buffer
LicenseProperty
Read a property value from the license XML document
ListFilesToTempTable
List files in a folder into a temporary table
LoadJson
Parse a JSON string into the AMSX JSON object for subsequent JsonValue or JsonSelect operations
LoadTextFile
Load a text file into the result buffer
LoadXML
Parse the result buffer as XML and load it into the AMSX XML buffer
LoadXMLFile
Load an XML file from disk into the AMSX XML buffer
LoadXMLText
Parse an inline XML string and load it into the AMSX XML buffer
LookupForm
Manage an xAssets lookup form used to populate fields from a related table
LookupForm.Create
Initialise a lookup form object from the current context
LookupForm.Get
Retrieve a named property from the active lookup form
MakeVariableSqlSafe
Mark a named variable as SQL-safe so it is inlined rather than parameterised
Menu
XDML definition block for Menu, Menu Category, or Menu Group
MergeParam
Merge a parameter or XML parameter block into the parameter collection
MergeSqlColumn
Merge the first column of a sql statement into a single field
MoveFile
Move a file to a new location
NewRecord
Create a new record in a metadata table
Next
End of for loop
NodeExists
Check if the current node exists
NodeName
Return the tag name of the currently selected XML node
Parameter
Get parameter
Parameters
Declare expected script parameters and initialise any that are missing
PositionDepreciation
Advance the depreciation position marker without recalculating depreciation values
PrintLast
Write the current result buffer to the log, preceded by a label
PrintXml
Add XML to the log
Query
XDML definition block for Query, Script, or Client Script
QueryCache
Cache a query result in a temporary table, running it only once per script execution
QueryString
Read a value from the parsed query string
QueryStringDate
Read a date value from the parsed query string
QueryStringEncode
URL-encode a string for use in a query string
QueryStringOptional
Read an optional value from the parsed query string
QueryToTempTable
Run a named query and load its results into a temporary table
QueryToTempTableWithSort
Run a named query and load its sorted results into a temporary table
QueryToXML
Run an xAssets saved query and load the result into the AMSX XML buffer
ReadCredentialPack
Read a stored credential pack into named variables
ReadJsonWebToken
Parse a JSON Web Token and store its claims into variables
ReadQueryString
Parse a query string and store it for later retrieval
RecogniseSoftware
Match raw software inventory records against the known software catalogue
RegexEscape
Regex escape
RegexUnescape
Regex unescape
Replace
Replace occurrences of a string in the result buffer, decoding special tokens first
ReplaceAll
Replace all occurrences of a string within a given string
ReplaceFirst
Replace the first occurrence of a string within a given string
ReplaceString
Replace all occurrences of a literal string in the result buffer
ReplaceURL
Rebuild a URL replacing the scheme, host, or port
Reset
Reset result
ResetAssetDefaultCache
Clear the in-memory cache of asset default field values
ResetPassword
Reset a user's password and optionally send a notification email
ResetSettingsCache
Clear the server-side settings cache
RestoreXMLFromVariable
Restore the AMSX XML document from a variable
ResultToFile
Save the result buffer to a file (ASCII)
ResultToFileUnicode
Save the result buffer to a file (Unicode)
ReturnReturnCode
Return a value and exit the script
Rewind
Rewind an accounting period, deleting previously calculated depreciation
Rollback
Rollback
RunReport
Run a saved query report and output it to a file or browser window
RunTransform
Run a named AMSX transform and place its result in the result buffer
SaveCredentialPack
Save a credential pack to the application or collection server
SaveNextAsset
Flag the engine to save only the first asset encountered during the next XMLSaver run
SaveSpecial
Run a SaveSpecial operation using the AMSX XML buffer
SaveSpecial1
Run a SaveSpecial operation using the AMSX XML buffer (no argument shift)
SaveSpecial2
Run a SaveSpecial operation with XML supplied as an argument
SaveSpecial3
Run a SaveSpecial operation with caret-delimited arguments
SaveSpecial4
Run a SaveSpecial operation with explicit XML and shifted arguments
SaveSpecialXML
Run a SaveSpecial operation using script input parameters as XML
SaveTextFile
Save the result buffer to a text file on the server
SaveTextFileAscii
Save the result buffer to a text file using ASCII encoding
SaveTextFileFromVariable
Save the contents of a variable to a text file on the server
SaveTextFilePrivate
Save the result buffer to a file in the private customer data area
SaveTextFilePrivateFromVariable
Save the value of a variable to a file in the private customer data area
SaveXML
Save the AMSX XML buffer to the database
SaveXMLFile
Save the current XML document to a file on the server
SaveXMLString
Save an XML string directly to the database
SelectParentNode
Set the current node to the parent node
SelectRootNode
Set the current node to the document root element
SelectSingleNode
Select a single XML node by field name and read its value
SelectSingleNodeDate
Select a single XML node and return its value as a normalised date string
SelectSingleNodeNoUntag
Select a single XML node by exact name without auto-tagging
SelectSingleNodeRelative
Set the current node to a relative node
SendEmail
Send an email to one or more recipients
SendToxAssets
Upload a file to an xAssets website
Serialize
Serialise a database table or object into XML, JSON, or AMSX text format
ServicePaused
Check whether a Windows service is paused
ServiceRunning
Check whether a Windows service is running
ServiceStopped
Check whether a Windows service is stopped
Set
Set the result buffer to a fixed value or variable
SetBatchJobForMeter
Set batch job for meter
SetBatchJobProgressMeter
Set batch progress
SetBatchJobStatus
Set Batch Job Status
SetCurrentPeriod
Set the current accounting period for a user's reporting dates
SetLaunch
Set the launch URL or command to be returned to the caller
SetNode
Set the node value
SetParams
Set parameters
SetReturnCode
Set the script return code
SetReturnValue
Copy the result buffer into the transform's string return value
SetSpecialOption
Create or update a special option setting value
SetText
Extract the collected SQL/text block into the result buffer
SetThreadPriority
Lower the thread priority for this script to avoid affecting system responsiveness
SetTransformResult
Capture the current result buffer as the transform's final return value
Sha256
Compute a SHA-256 hash of a string and return it as a Base64-URL-encoded value
Sleep
Pause script execution for a specified number of milliseconds
Snmp
Perform SNMP operations such as reading MIB files
Snmp.ReadMibFile
Read an SNMP MIB file into a temporary table
SpecialOption
Read a special option setting value
SplitString
Split a string by a delimiter and return the element at a given position
Sql
Execute a SQL statement and place the first value of the result in the result buffer
SqlBatch
Execute a SQL statement on the batch processor's dedicated database connection
SqlCsv
Execute a SQL statement and return the result as a CSV string
SqlDate
Execute a SQL statement and return the result as a date value
SqlInList
Store a comma-separated list as a SQL-safe IN list variable
SqlInListValues
Store a list as a SQL-safe parameterised VALUES list for bulk INSERT statements
SqlOntoXML
Overlay Sql onto XML
SqlSet
Execute a SQL statement and assign its columns to named variables
SqlSnippet
Store a SQL-safe string in a variable for use in SQL statement construction
SqlStatement
Build and execute dynamic SQL statements using a fluent sub-command API
SqlStatement.AddAPIFIeld
Add an API-expression field to a SQL statement variable
SqlStatement.AddBaseTableFields
Add all base table fields to a SQL statement variable's SELECT list
SqlStatement.AddCTE
Wrap a SQL statement variable in a Common Table Expression
SqlStatement.AddJoin
Add a JOIN clause to a SQL statement variable
SqlStatement.AddParameter
Add a named parameter to a SQL statement variable
SqlStatement.AddWhereClause
Add a WHERE condition to a SQL statement variable
SqlStatement.BaseTable
Set the base table on a SQL statement variable
SqlStatement.ClearFieldList
Remove all fields from the SELECT list of a SQL statement variable
SqlStatement.ClearGroupBy
Remove the GROUP BY clause from a SQL statement variable
SqlStatement.ClearOrderBy
Remove the ORDER BY clause from a SQL statement variable
SqlStatement.CreateFromQuery
Build a SQL statement variable from a saved xAssets query definition
SqlStatement.Dump
Dump the generated SQL text of a SQL statement variable to the result buffer
SqlStatement.FieldList
Add fields to a SQL statement variable's SELECT list
SqlStatement.GenerateGroupByClause
Derive a GROUP BY clause automatically from the SELECT field list
SqlStatement.GroupBy
Add GROUP BY fields to a SQL statement variable
SqlStatement.HavingClause
Add a HAVING clause to a SQL statement variable
SqlStatement.InsertInto
Insert the results of a SQL statement variable into an existing table
SqlStatement.Merge
Merge one SQL statement variable into another
SqlStatement.OrderBy
Add ORDER BY fields to a SQL statement variable
SqlStatement.SelectInto
Execute a SQL statement variable and store the results in a new temp table
SqlStatement.SetFields
Replace the SELECT field list of a SQL statement variable
SqlStatement.SetOrderByToGroupBy
Copy the GROUP BY fields into the ORDER BY clause of a SQL statement variable
SqlStatement.Sql
Render a SQL statement variable into the collected SQL buffer
SqlStatement.SqlSet
Execute a SQL statement variable and assign column values to named AMSX variables
SqlStatement.TopRecords
Limit the number of rows returned by a SQL statement variable
SqlStatement.WhereClause
Read the current WHERE clause text from a SQL statement variable
SqlTextOntoXML
Overlay Sql text onto XML
SqlToXML
Execute a SQL statement and load the results into the AMSX XML buffer
StartService
Start a Windows service if it is currently stopped
StopService
Stop a Windows service if it is currently running
StringToHex
Convert a string to its Unicode hex representation
Substring
Extract a substring from a string
SwitchUser
Switch the current execution context to a different user
SyncDatabase
Synchronise data from a source database into the current database
SyncPeriodTable
Synchronise the accounting period table to match the current date
TableExists
Check whether a database table or temp table exists and return true or false
TableWordExpand
Expand and normalise word tokens in a table column using SQL-driven rules
Test
Run assertion tests against database table contents
Test.Count
Assert that the number of rows in a table matches an expected count
Test.Exists
Assert that at least one row matching a WHERE condition exists in a table
TestQuery
Validate that a saved xAssets query executes without errors
Text
Mark the start of a text block (processed in header)
TextToXML
Text to XML
Throw
Raise an exception and abort the script
Touch
Update a file's last-modified timestamp to the current time
Trim
Trim whitespace or a specific character from a string
TryDelete
Attempt to delete a file, ignoring errors if it cannot be deleted
Unescape
Unescape
UnescapeFull
Unescape full
UniqueID
Get the Form ID
UnzipNet
Extract a zip archive using the .NET ZipFile class
UnzipString
Decompress a Base64-encoded compressed string
UploadFile
Upload a local file to a URL
UploadFileSecure
Upload a local file to an authenticated URL
URLSetValue
Set or update a query-string parameter on a URL
ValueListFromURL
Extract the values from a URL query string
ValueTest
Assert that two values are equal, throwing an error if they differ
WaitForDueFiles
Wait until a minimum number of discovery files are ready to process
WaitForFileExists
Wait until a file appears on the file system within a timeout period
WaitForFileToUnlock
Wait until a file is no longer locked by another process
WriteJournals
Write accounting journals for an accounting period set up to a specified date
XmlAddColumn
Add a column to every row in the XML document
XmlAddColumnNoTag
Add a column to every row in the XML document without tag conversion
XmlChangeTable
Rename the root node of the XML document
XmlClean
Clean XML
XmlFileToTable
Load an XML dataset file from disk and create temporary tables from its contents
XmlFilterList
Extract a comma-separated list of values from the XML document matching a filter
XmlGet
Read a field value from the XML document into the result buffer
XmlRemoveColumn
Remove a column from every row in the XML document
XmlRemoveColumnNoTag
Remove a column from every row in the XML document without tag conversion
XmlSet
Write a value into a field node in the XML document
XmlSetNode
Write a value into a field node of the current XML record (mnod)
XmlTest
Test two fields in the XML document for equality and report differences
XmlToCSV
Convert the current XML document to a delimited text string
XmlToHtml
Convert the XML buffer to an HTML table string
XmlToJson
Convert the XML buffer to a JSON string
XmlToTempTable
Load the current XML document into a temporary database table
XmlToTempTableAppend
Append the XML buffer to a temporary table, adding rows without recreating the table
ZipNet
Compress a file or folder using the .NET ZipFile class
ZipString
Compress a string and return it as a Base64-encoded value