ServiceNow Connector for PowerShell How to Get Table Rows
Introduction
In this article we will delve deeper into ServiceNow and PowerShell integration, and will learn how to get table rows. We are continuing from where we left off. By this time, you must have installed ODBC PowerPack, created ODBC Data Source, and configured authentication settings in your ServiceNow account .
So, let's not waste time and begin.
Use Query Builder to generate SQL query
-
The first thing you have to do is open Query Builder:
ZappySys API Driver - ServiceNowRead and write ServiceNow data effortlessly. Integrate, manage, and automate incidents, tasks, attachments, and records — almost no coding required.ServicenowDSN
-
Then simply select the Get Table Rows endpoint (action).
-
Continue by configuring the Required parameters. You can also set optional parameters too.
-
Move on by hitting Preview Data button to preview the results.
-
If you see the results you need, simply copy the generated query:
-
That's it! You can use this query in PowerShell.
Let's not stop here and explore SQL query examples, including how to use them in Stored Procedures and Views (virtual tables) in the next steps.
SQL query examples
Use these SQL queries in your PowerShell data source:
How to Get a list of incidents
SELECT * FROM incident
--Using Primary Key
--SELECT * FROM any_table_here WHERE sys_id='109562a3c611227500a7b7ff98cc0dc7' --Primary Key in WHERE clause
--OR--
--Use below to query system / hidden tables (faster response - No Table name lookup needed in below)
SELECT * FROM get_table_rows WITH(TableName='incident', Query='number=INC0000001')
--=================================
--Examples: Using Filter Expression
--=================================
-- Incremental Load Pattern: Load only incidents updated in the last 24 hours (see FUN_TO_DATETIME function help for more information, you can use +/- d, m, y, min,h,s along with now, today, yesterday, weekstart, weekend, monthstart, monthend, yearstart, yearend functions)
--SELECT * FROM incident WITH(Query='sys_updated_on>=<<today-1d,FUN_TO_DATETIME>>'
--SELECT * FROM incident WITH(Query='number=INC0000001') --Equal condition
--SELECT * FROM incident WITH(Query='number!=INC0000001') --Not equal condition
--SELECT * FROM incident WITH(Query='numberININC0000001,INC0000002,INC0000003') --IN condition
--SELECT * FROM incident WITH(Query='number=INC0000001^state=7') --AND condition
--SELECT * FROM incident WITH(Query='number=INC0000001^ORnumber=INC0000002') --OR condition
--SELECT * FROM incident WITH(Query='numberLIKE0001') --LIKE condition
--SELECT * FROM incident WITH(Query='numberSTARTSWITHINC00') --StartWith condition
--SELECT * FROM incident WITH(Query='numberENDSWITH0001') --StartWith condition
--SELECT * FROM incident WITH(Query='number=INC0000001^state=7^NQORnumber=INC0000002') --AND / OR MIXED using NQ (NewQuery Operator) -- (number=INC0000001 and state=7) OR (number=INC0000002)
--more information about filter here https://docs.servicenow.com/bundle/utah-platform-user-interface/page/use/common-ui-elements/reference/r_OpAvailableFiltersQueries.html
-- To read all available tables execute this query:
-- SELECT * FROM Tables
-- Other common tables:
-----------------------
-- SELECT * FROM sys_db_object
-- SELECT * FROM sys_dictionary
-- SELECT * FROM sys_user
-- SELECT * FROM sys_user_has_role
-- SELECT * FROM sys_user_grmember
-- SELECT * FROM task
-- SELECT * FROM task_sla
-- SELECT * FROM incident
-- SELECT * FROM incident_sla
-- SELECT * FROM change_request
-- SELECT * FROM cmdb_ci_computer
-- SELECT * FROM cmdb_ci_outage
-- SELECT * FROM cmdb_ci
-- SELECT * FROM sn_customerservice_case
-- SELECT * FROM kb_knowledge
-- SELECT * FROM kb_use
-- SELECT * FROM sc_req_item
-- SELECT * FROM sc_request
-- SELECT * FROM sc_task
How to Incremental Incident Sync Using Updated Date
-- Incrementally fetch incidents updated after a given date
SELECT *
FROM get_table_rows
WITH(
TableName='incident',
- Load only incidents updated in the last 24 hours
Query='sys_updated_on>=<<today-1d,FUN_TO_DATETIME>>'
--OR Updated after static date time
--Query='sys_updated_on>=2025-01-01T23:23:59'
--Query='sys_updated_on>=2025-01-01'
--Other examples of placeholder function usage
--Query='sys_updated_on>=<<monthstart-7d,FUN_TO_DATETIME>>'
--Query='sys_updated_on>=<<monthstart-5d+1y,FUN_TO_DATETIME>>'
)
How to Get data from system table (internal hidden table)
This example shows how to query system table (e.g. sys_choice, sys_journal_field). Many tables not listed in get_tables endpoint so hidden from UI selection. Use get_table_rows endpoint in that case.
SELECT * FROM get_table_rows WITH(TableName='sys_choice', Query='name=incident^element=close_code')
--SELECT * FROM get_table_rows WITH(TableName='sys_journal_field', Query='name=incident^element=close_code')
How to Query Incident by Incident Number
-- Query a single incident by incident number
SELECT *
FROM get_table_rows
WITH(
TableName='incident',
Query='number=INC0012345'
)
How to Get Incident Work Notes (Journal Entries)
-- Get work notes for all incidents
SELECT *
FROM get_table_rows
WITH(
TableName='sys_journal_field',
Query='name=incident^element=work_notes'
)
How to Get Incident Additional Comments
-- Get customer-facing comments for incidents
SELECT *
FROM get_table_rows
WITH(
TableName='sys_journal_field',
Query='name=incident^element=comments'
)
How to Query Incident Tasks by Parent Incident
-- Get all tasks for a specific incident
SELECT *
FROM get_table_rows
WITH(
TableName='incident_task',
Query='incident.number=INC0012345'
)
How to List Attachments for an Incident
-- List attachments linked to an incident
SELECT *
FROM get_table_rows
WITH(
TableName='sys_attachment',
Query='table_name=incident^table_sys_id=<<INCIDENT_SYS_ID>>'
)
How to Resolve and List Dropdown Labels and Values (Any ServiceNow Table)
-- Resolve and list dropdown (choice) labels and values for any table and field
-- Replace <TABLE_NAME> and <FIELD_NAME> with your target form field (e.g. name=incident^element=priority)
SELECT *
FROM get_table_rows
WITH(
TableName='sys_choice',
Query='name=<TABLE_NAME>^element=<FIELD_NAME>'
)
How to Query Incident Using Reference (Foreign Key) Fields
-- 1. Query incidents by caller's username (caller_id → sys_user)
SELECT *
FROM get_table_rows
WITH(
TableName='incident',
Query='caller_id.user_name=john.doe'
)
-- 2. Query incidents by assigned user's display name (assigned_to → sys_user)
SELECT *
FROM get_table_rows
WITH(
TableName='incident',
Query='assigned_to.name=Jane Smith'
)
-- 3. Query incidents by assignment group name (assignment_group → sys_user_group)
SELECT *
FROM get_table_rows
WITH(
TableName='incident',
Query='assignment_group.name=Network'
)
-- 4. Query incidents by configuration item name (cmdb_ci → CMDB record)
SELECT *
FROM get_table_rows
WITH(
TableName='incident',
Query='cmdb_ci.name=SRV-APP-01'
)
-- 5. Combine reference field and local field filters
-- (Network group + High priority incidents)
SELECT *
FROM get_table_rows
WITH(
TableName='incident',
Query='assignment_group.name=Network^priority=1'
)
How to Get only selected columns and speed up the query
By default all column values are returned in the result set. However, you can instruct the ServiceNow API to send only specific columns you care about by setting 'Fields' parameter in the WITH clause. This will speed up the response significantly.
SELECT number,name FROM incident WITH (Fields='number,name') --Setting Fields parameter will speed up the query
How to Query table using serverside filter expression
-- Basic server-side filter
SELECT * FROM incident WITH(Query='state=2')
-- Primary key lookup (fastest)
SELECT * FROM incident WHERE sys_id='109562a3c611227500a7b7ff98cc0dc7'
-- Not equal
SELECT * FROM incident WITH(Query='state!=6')
-- IN condition
SELECT * FROM incident WITH(Query='priorityIN1,2,3')
-- AND condition
SELECT * FROM incident WITH(Query='priority=1^state=2')
-- SQL: WHERE priority = 1 AND state = 2
-- OR condition (same group)
SELECT * FROM incident WITH(Query='priority=1^ORstate=2')
-- SQL: WHERE priority = 1 OR state = 2
-- AND / OR mixed using NQ
SELECT * FROM incident WITH(Query='priority=1^state=2^NQpriority=2^state=3')
-- SQL: (priority = 1 AND state = 2) OR (priority = 2 AND state = 3)
-- LIKE / StartsWith / EndsWith
SELECT * FROM incident WITH(Query='short_descriptionLIKEemail')
SELECT * FROM incident WITH(Query='numberSTARTSWITHINC')
SELECT * FROM incident WITH(Query='numberENDSWITH001')
-- Date filter using placeholders (last 1 month)
SELECT * FROM incident WITH(Query='opened_at>=<<today-1m,FUN_TO_DATE>>')
-- From month start
SELECT * FROM incident WITH(Query='opened_at>=<<monthstart,FUN_TO_DATE>>')
-- Between dates
SELECT * FROM incident WITH(Query='opened_at>=<<monthstart,FUN_TO_DATE>>^opened_at<=<<monthend,FUN_TO_DATE>>')
How to Get a list of system tables
SELECT * FROM SystemTables
How to Get a list of user tables
SELECT * FROM UserTables
How to Download Table Attachment (Single - Using Id)
-- Download a single attachment by sys_id to a custom file path (always overwrite if exists)
SELECT * FROM download_attachment_single
WITH(
SysId='4b2d41168396b21032ddb9f6feaad38f',
TargetFilePath='c:\temp\dump_saved.png',
--Set overwrite mode : 0=AlwaysOverwrite, 1=FailIfExists, 2=SkipIfExists
FileOverwriteMode=0
)
-- Download another attachment with a different name (fail if file exists)
SELECT * FROM download_attachment_single
WITH(
SysId='another_attachment_sys_id_here',
TargetFilePath='c:\downloads\report.pdf',
FileOverwriteMode='FailIfExists'
)
-- Download using numeric value for skip if exists
SELECT * FROM download_attachment_single
WITH(
SysId='third_attachment_sys_id_here',
TargetFilePath='c:\files\data.xlsx',
FileOverwriteMode=2
)
How to Get an incident by sys_id
SELECT * FROM incident
WHERE sys_id = 'SYS_ID_GOES_HERE'
How to Query table using serverside filter expression
-- Basic server-side filter
SELECT * FROM incident WITH(Query='state=2')
-- Primary key lookup (fastest)
SELECT * FROM incident WHERE sys_id='109562a3c611227500a7b7ff98cc0dc7'
-- Not equal
SELECT * FROM incident WITH(Query='state!=6')
-- IN condition
SELECT * FROM incident WITH(Query='priorityIN1,2,3')
-- AND condition
SELECT * FROM incident WITH(Query='priority=1^state=2')
-- SQL: WHERE priority = 1 AND state = 2
-- OR condition (same group)
SELECT * FROM incident WITH(Query='priority=1^ORstate=2')
-- SQL: WHERE priority = 1 OR state = 2
-- AND / OR mixed using NQ
SELECT * FROM incident WITH(Query='priority=1^state=2^NQpriority=2^state=3')
-- SQL: (priority = 1 AND state = 2) OR (priority = 2 AND state = 3)
-- LIKE / StartsWith / EndsWith
SELECT * FROM incident WITH(Query='short_descriptionLIKEemail')
SELECT * FROM incident WITH(Query='numberSTARTSWITHINC')
SELECT * FROM incident WITH(Query='numberENDSWITH001')
-- Date filter using placeholders (last 1 month)
SELECT * FROM incident WITH(Query='opened_at>=<<today-1m,FUN_TO_DATE>>')
-- From month start
SELECT * FROM incident WITH(Query='opened_at>=<<monthstart,FUN_TO_DATE>>')
-- Between dates
SELECT * FROM incident WITH(Query='opened_at>=<<monthstart,FUN_TO_DATE>>^opened_at<=<<monthend,FUN_TO_DATE>>')
get_table_rows endpoint belongs to
[Dynamic Table]
table(s), and can therefore be used via those table(s).
Stored Procedures and Views
Create Custom Stored Procedure
You can create procedures to encapsulate custom logic and then only pass handful parameters rather than long SQL to execute your API call.
Steps to create Custom Stored Procedure in ZappySys Driver. You can insert Placeholders anywhere inside Procedure Body. Read more about placeholders here
-
Go to Custom Objects Tab and Click on Add button and Select Add Procedure:
-
Enter the desired Procedure name and click on OK:
-
Select the created Stored Procedure and write the your desired stored procedure and Save it and it will create the custom stored procedure in the ZappySys Driver:
Here is an example stored procedure for ZappySys Driver. You can insert Placeholders anywhere inside Procedure Body. Read more about placeholders here
CREATE PROCEDURE [usp_get_orders] @fromdate = '<<yyyy-MM-dd,FUN_TODAY>>' AS SELECT * FROM Orders where OrderDate >= '<@fromdate>';
-
That's it now go to Preview Tab and Execute your Stored Procedure using Exec Command. In this example it will extract the orders from the date 1996-01-01:
Exec usp_get_orders '1996-01-01';
Create Custom Virtual Table
ZappySys API Drivers support flexible Query language so you can override Default Properties you configured on Data Source such as URL, Body. This way you don't have to create multiple Data Sources if you like to read data from multiple EndPoints. However not every application support supplying custom SQL to driver so you can only select Table from list returned from driver.
If you're dealing with Microsoft Access and need to import data from an SQL query, it's important to note that Access doesn't allow direct import of SQL queries. Instead, you can create custom objects (Virtual Tables) to handle the import process.
Many applications like MS Access, Informatica Designer wont give you option to specify custom SQL when you import Objects. In such case Virtual Table is very useful. You can create many Virtual Tables on the same Data Source (e.g. If you have 50 URLs with slight variations you can create virtual tables with just URL as Parameter setting.
-
Go to Custom Objects Tab and Click on Add button and Select Add Table:
-
Enter the desired Table name and click on OK:
-
And it will open the New Query Window Click on Cancel to close that window and go to Custom Objects Tab.
-
Select the created table, Select Text Type AS SQL and write the your desired SQL Query and Save it and it will create the custom table in the ZappySys Driver:
Here is an example SQL query for ZappySys Driver. You can insert Placeholders also. Read more about placeholders here
SELECT "ShipCountry", "OrderID", "CustomerID", "EmployeeID", "OrderDate", "RequiredDate", "ShippedDate", "ShipVia", "Freight", "ShipName", "ShipAddress", "ShipCity", "ShipRegion", "ShipPostalCode" FROM "Orders" Where "ShipCountry"='USA'
-
That's it now go to Preview Tab and Execute your custom virtual table query. In this example it will extract the orders for the USA Shipping Country only:
SELECT * FROM "vt__usa_orders_only"
Get Table Rows in PowerShell
-
Open your favorite PowerShell IDE (we are using Visual Studio Code).
-
Use this code snippet to read the data using
ServicenowDSNdata source:"DSN=ServicenowDSN"
For your convenience, here is the whole PowerShell script:
# Configure connection string and query $connectionString = "DSN=ServicenowDSN" $query = "SELECT * FROM Customers" # Instantiate OdbcDataAdapter and DataTable $adapter = New-Object System.Data.Odbc.OdbcDataAdapter($query, $connectionString) $table = New-Object System.Data.DataTable # Fill the table with data $adapter.Fill($table) # Since we know we will be reading just 4 columns, let's define format for those 4 columns, each separated by a tab $format = "{0}`t{1}`t{2}`t{3}" # Display data in the console foreach ($row in $table.Rows) { # Construct line based on the format and individual ServiceNow fields $line = $format -f ($row["CustomerId"], $row["CompanyName"], $row["Country"], $row["Phone"]) Write-Host $line }Access specific ServiceNow table field using this code snippet:
You will find more info on how to manipulate$field = $row["ColumnName"]DataTable.Rowsproperty in Microsoft .NET reference.For demonstration purposes we are using sample tables which may not be available in ServiceNow. -
To read values in a console, save the script to a file and then execute this command inside PowerShell terminal:
You can also use even a simpler command inside the terminal, e.g.:. 'C:\Users\john\Documents\dsn.ps1'
More actions supported by ServiceNow Connector
Learn how to perform other actions directly in PowerShell with these how-to guides:
- Delete a Table Row
- Delete Attachment
- Delete table row
- Download Table Attachment (Single - Using Id)
- Download Table Attachments (Multiple - Using Query)
- Download Table Attachments By Parent Row Search
- Get Attachments
- Get Attachments By Parent Row Search
- Get List Of System Tables Admin Use Sys Db Object
- Get List of Tables
- Get List Of Tables Admin Use Sys Db Object
- Get List Of User Tables Admin Use Sys Db Object
- Get Record Labels (Tags)
- Get Table Columns
- Get Table Columns Admin Use Sys Dictionary
- Get Table Row Count
- Test Connection
- Update a Table Row
- Upload Attachment
- Make Generic API Request
- Make Generic API Request (Bulk Write)