### Create ServiceNow Configuration Items using PowerShell Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Shows how to create configuration item (CI) records in the CMDB. Examples include creating a server CI with detailed custom fields and creating a network device CI. Requires the New-ServiceNowConfigurationItem cmdlet. ```powershell # Create server CI $params = @{ Name = 'APP-SERVER-12' ShortDescription = 'Application Server 12' CustomField = @{ asset_tag = 'IT-2025-0123' serial_number = 'SN987654321' ip_address = '10.0.1.45' location = 'Datacenter 1 - Rack 15' environment = 'Production' manufacturer = 'Dell' model_id = 'PowerEdge R750' } PassThru = $true } $ci = New-ServiceNowConfigurationItem @params # Create network device CI $params = @{ Name = 'SWITCH-CORE-01' ShortDescription = 'Core Network Switch 01' CustomField = @{ asset_tag = 'NET-2025-0001' ip_address = '10.0.0.1' managed_by = 'network.team' support_group = 'Network Operations' } } New-ServiceNowConfigurationItem @params ``` -------------------------------- ### Create Generic ServiceNow Records (PowerShell) Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Demonstrates the generic New-ServiceNowRecord cmdlet for creating records in any ServiceNow table. It shows examples for creating incidents, custom table records, configuration items, and knowledge articles by providing a hashtable of values. ```powershell # Create incident using generic function $values = @{ caller_id = 'john.doe' short_description = 'Printer not working' description = 'Office printer 3rd floor not responding' category = 'Hardware' urgency = 3 impact = 3 } New-ServiceNowRecord -Table incident -Values $values -PassThru # Create custom table record $customValues = @{ u_application_name = 'HR Portal' u_owner = 'jane.smith' u_environment = 'Production' u_status = 'Active' } New-ServiceNowRecord -Table 'u_custom_app_registry' -Values $customValues # Create configuration item $ciValues = @{ name = 'WEB-SERVER-05' asset_tag = 'IT-2025-0045' serial_number = 'SN123456789' model_id = 'Dell PowerEdge R740' assigned_to = 'datacenter.team' location = 'Building A - Datacenter' } New-ServiceNowRecord -Table cmdb_ci_server -Values $ciValues -PassThru # Create knowledge article $kbValues = @{ short_description = 'How to reset password' text = '

Password Reset Process

Follow these steps...

' kb_category = 'Self Service' workflow_state = 'draft' } New-ServiceNowRecord -Table kb_knowledge -Values $kbValues -PassThru ``` -------------------------------- ### Create ServiceNow Change Tasks using PowerShell Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Provides examples for creating change task records associated with change requests. It covers basic creation with essential fields and advanced creation including custom fields and returning the created object. Requires the New-ServiceNowChangeTask cmdlet. ```powershell # Basic change task creation $params = @{ ChangeRequest = 'CHG0010001' ShortDescription = 'Backup database before upgrade' Description = 'Create full backup of production database' AssignmentGroup = 'Database Team' } New-ServiceNowChangeTask @params # Change task with custom fields $params = @{ ChangeRequest = 'CHG0010002' ShortDescription = 'Update load balancer configuration' AssignmentGroup = 'Network Operations' CustomField = @{ planned_start_date = (Get-Date).AddDays(7).ToString('yyyy-MM-dd HH:mm:ss') planned_end_date = (Get-Date).AddDays(7).AddHours(2).ToString('yyyy-MM-dd HH:mm:ss') u_task_type = 'Configuration' } PassThru = $true } $task = New-ServiceNowChangeTask @params ``` -------------------------------- ### Create ServiceNow Change Request Records Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Illustrates creating change request records in ServiceNow using New-ServiceNowChangeRequest. Examples cover basic creation, adding detailed fields, creating from change models, and using standard change templates with custom fields. ```powershell # Basic change request creation New-ServiceNowChangeRequest -Caller 'greg.brownstein' -ShortDescription 'Patch application servers' -Description 'Apply security patches to production app servers' # Change request with additional fields $params = @{ Caller = 'admin' ShortDescription = 'Database schema update' Description = 'Update customer database schema for new features' AssignmentGroup = 'Database Administrators' Category = 'Database' ConfigurationItem = 'PROD-DB-01' CustomField = @{ urgency = 2 impact = 2 risk = 'Medium' justification = 'Required for Q4 release' implementation_plan = 'Run migration scripts during maintenance window' backout_plan = 'Restore from backup if issues occur' test_plan = 'Verify application connectivity post-change' } PassThru = $true } $change = New-ServiceNowChangeRequest @params # Create from change model New-ServiceNowChangeRequest -ModelID 'Normal' -ShortDescription 'Firewall rule update' -ConfigurationItem 'FW-PROD-01' # Create from standard change template New-ServiceNowChangeRequest -TemplateID 'Add user to Active Directory group' -CustomField @{ u_username = 'john.doe' u_group_name = 'Finance_Users' } ``` -------------------------------- ### Create ServiceNow Incident Records Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Provides examples for creating new incident records in ServiceNow using the New-ServiceNowIncident cmdlet. Supports basic fields, custom fields via CustomField parameter, and returning the created record with PassThru. It also shows how to attach files to newly created incidents. ```powershell # Basic incident creation $params = @{ Caller = "john.doe" ShortDescription = "Application login failure" Description = "Users unable to login to CRM application since 9am" AssignmentGroup = "Application Support" Category = "Software" Subcategory = "Application" Comment = "Reported by multiple users" } New-ServiceNowIncident @params # Incident with custom fields and return created record $params = @{ Caller = "jane.smith" ShortDescription = "VPN connection issues" Description = "Cannot establish VPN connection from home office" ConfigurationItem = "VPN-Gateway-01" CustomField = @{ urgency = 1 impact = 2 u_location = "Remote Office" u_department = "Sales" business_service = "Remote Access Services" } PassThru = $true } $newIncident = New-ServiceNowIncident @params Write-Host "Created incident: $($newIncident.number)" # Create incident and immediately add attachment $incident = New-ServiceNowIncident -Caller "admin" -ShortDescription "Server disk space issue" -PassThru $incident | Add-ServiceNowAttachment -File "C:\Logs\server_status.txt" ``` -------------------------------- ### Add Attachments to ServiceNow Records (PowerShell) Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt This section details how to use the Add-ServiceNowAttachment cmdlet to upload files to ServiceNow records. Examples include adding single and multiple files, specifying table and sys_id, overriding content type, and using pipeline input. ```powershell # Add single attachment by record number Add-ServiceNowAttachment -Id 'INC0010001' -File 'C:\Logs\error_log.txt' # Add multiple attachments Add-ServiceNowAttachment -Id 'CHG0010002' -File @('C:\Docs\plan.pdf', 'C:\Docs\approval.pdf') # Add with explicit table and sys_id Add-ServiceNowAttachment -Table incident -Id '8e7f9a1b2c3d4e5f6a7b8c9d0e1f2a3b' -File 'C:\Screenshots\error.png' # Override content type Add-ServiceNowAttachment -Id 'INC0010003' -File 'C:\Data\export.dat' -ContentType 'application/octet-stream' # Add attachment and get file details back $attachment = Add-ServiceNowAttachment -Id 'RITM0010001' -File 'C:\Forms\request_form.pdf' -PassThru Write-Host "Uploaded: $($attachment.file_name), Size: $($attachment.size_bytes) bytes" # Pipeline from record creation $incident = New-ServiceNowIncident -Caller 'user1' -ShortDescription 'Issue report' -PassThru $incident | Add-ServiceNowAttachment -File 'C:\Reports\diagnostic_report.html' # Add attachments to multiple records Get-ServiceNowRecord -Table incident -Filter @('assigned_to', '-eq', 'admin'), '-and', @('state', '-eq', '2') | Add-ServiceNowAttachment -File 'C:\Updates\status_update.pdf' ``` -------------------------------- ### Remove ServiceNow Records (PowerShell) Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Provides examples for removing records from ServiceNow using the Remove-ServiceNowRecord cmdlet. It covers removing single records by ID, bulk removal from pipeline, and removing records based on specific filters with or without confirmation. ```powershell # Remove single record by number (with confirmation) Remove-ServiceNowRecord -ID 'CHG0010005' # Remove without confirmation prompt Remove-ServiceNowRecord -ID 'INC0010003' -Confirm:$false # Remove by table and sys_id Remove-ServiceNowRecord -Table incident -ID '7b6e8e9c1bafc9100774ebd1b24bcb23' # Bulk remove from pipeline Get-ServiceNowRecord -Table incident -Filter @('state', '-eq', '7'), '-and', @('closed_at', '-lt', (Get-Date).AddYears(-2)) | Remove-ServiceNowRecord -Confirm:$false # Remove specific records with confirmation for each Get-ServiceNowRecord -Table 'change_request' -Description 'test' | Where-Object { $_.short_description -like '*sandbox*' } | Remove-ServiceNowRecord ``` -------------------------------- ### Get ServiceNow Incidents (Last 30 Days) Source: https://github.com/snow-shell/servicenow-powershell/blob/master/Readme.md Retrieves incident records from ServiceNow that were opened in the last 30 days. It utilizes the Get-ServiceNowRecord cmdlet and filters by the 'opened_at' field. Assumes an active ServiceNow session. ```powershell Get-ServiceNowRecord -Table incident -Filter @('opened_at', '-ge', (Get-Date).AddDays(-30)) ``` -------------------------------- ### Query ServiceNow Records and Process with Pipelines Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Demonstrates querying ServiceNow records using the Get-ServiceNowRecord cmdlet with date range filters and state equality. It also shows how to pipe the results to Where-Object and ForEach-Object for further processing and updating records with Update-ServiceNowRecord. ```powershell # Between operator for date ranges Get-ServiceNowRecord -Table incident -Filter @('opened_at', '-between', (Get-Date).AddMonths(-12), (Get-Date).AddMonths(-6)) # Pipeline processing Get-ServiceNowRecord -Table incident -Filter @('state', '-eq', '1') | Where-Object { $_.priority -eq '1' } | ForEach-Object { Update-ServiceNowRecord -ID $_.sys_id -InputData @{'assigned_to' = 'admin'} } ``` -------------------------------- ### Create ServiceNow Change Request and Add Attachments (PowerShell) Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt This snippet demonstrates how to create a new ServiceNow change request and then attach multiple supporting documentation files to it. It utilizes the New-ServiceNowChangeRequest and Add-ServiceNowAttachment cmdlets. ```powershell $chg = New-ServiceNowChangeRequest -Caller 'admin' -ShortDescription 'Server migration' -PassThru $chg | Add-ServiceNowAttachment -File @('C:\Docs\migration_plan.pdf', 'C:\Docs\rollback_procedure.pdf') ``` -------------------------------- ### Create ServiceNow Session (Basic Auth) Source: https://github.com/snow-shell/servicenow-powershell/blob/master/Readme.md Establishes a new session with ServiceNow using basic authentication with a username and password. This session is stored in the $ServiceNowSession variable for subsequent cmdlets. Requires PowerShell 5.1+ and a ServiceNow tenant with appropriate API access. ```powershell $params = @{ Url = 'instance.service-now.com' Credential = $userCred } New-ServiceNowSession @params ``` -------------------------------- ### Azure Automation Integration Module Connection Source: https://github.com/snow-shell/servicenow-powershell/blob/master/Readme.md Demonstrates how to use the ServiceNow module with Azure Automation integration modules by providing a connection object. The 'Connection' parameter accepts a hashtable with username, password, and ServiceNow URL. This facilitates integration with Azure cloud services. ```powershell # The 'Connection' parameter accepts a hashtable object that requires a username, password, and ServiceNowURL. # Example: # $connection = @{ # username = "your_username" # password = "your_password" # ServiceNowURL = "your_instance.service-now.com" # } # Get-ServiceNowRecord -Connection $connection -Table incident ``` -------------------------------- ### Query ServiceNow with Variables using PowerShell Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Demonstrates how to perform a GraphQL query against the ServiceNow API using variables for dynamic filtering. This is useful for fetching specific records based on parameters like incident IDs. It requires the Invoke-ServiceNowGraphQL cmdlet. ```powershell $query = @" query GetIncident(`$incidentId: String!) { incident(filter: {number: {equals: `$incidentId}}) { number short_description state priority } } "@ $variables = @{ incidentId = "INC0010001" } $result = Invoke-ServiceNowGraphQL -Query $query -Variables $variables ``` -------------------------------- ### Create ServiceNow Session (OAuth/Client Credential) Source: https://github.com/snow-shell/servicenow-powershell/blob/master/Readme.md Creates a new ServiceNow session using OAuth with user credentials and optionally application/client credentials. The module automatically handles token refresh. This is suitable for scenarios requiring OAuth authentication. Requires PowerShell 5.1+ and a ServiceNow tenant with a configured OAuth application. ```powershell $params = @{ Url = 'instance.service-now.com' Credential = $userCred ClientCredential = $clientCred } New-ServiceNowSession @params ``` -------------------------------- ### Create ServiceNow Session with New-ServiceNowSession (PowerShell) Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Establishes an authenticated session to a ServiceNow instance. Supports basic authentication, OAuth 2.0 with token refresh, proxy configurations, custom timeouts, and pre-generated access tokens. The created session is automatically used by other cmdlets or can be explicitly passed using the ServiceNowSession parameter. Supports multiple API versions. ```powershell # Basic authentication session $credential = Get-Credential New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential # OAuth 2.0 authentication with automatic token refresh $userCred = Get-Credential -Message "Enter ServiceNow username and password" $clientCred = Get-Credential -Message "Enter OAuth Client ID as username and Client Secret as password" New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $userCred -ClientCredential $clientCred # Session with proxy and custom timeout $proxyCred = Get-Credential -Message "Proxy credentials" New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential -Proxy 'http://proxy.company.com:8080' -ProxyCredential $proxyCred -TimeoutSec 300 # Using pre-generated access token New-ServiceNowSession -Url 'myinstance.service-now.com' -AccessToken 'a9f8h34kjh5g43kj5h34g5k3j4h5g34' # Multiple sessions with PassThru for different API versions $sessionV1 = New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential -ApiVersion 1 -PassThru $sessionV2 = New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential -ApiVersion 2 -PassThru Get-ServiceNowRecord -Table incident -ID 'INC0010001' -ServiceNowSession $sessionV1 ``` -------------------------------- ### Create ServiceNow Incident Source: https://github.com/snow-shell/servicenow-powershell/blob/master/Readme.md Creates a new incident in ServiceNow with specified caller, short description, and detailed description. It also allows for setting custom table entries like 'u_service', 'u_incident_type', and 'urgency'. Assumes an active ServiceNow session. ```powershell $params = @{ Caller = "UserName" ShortDescription = "New PS Incident" Description = "This incident was created from Powershell" InputData = @{ u_service = "MyService" u_incident_type = "Request" urgency = 1 } } New-ServiceNowIncident @params ``` -------------------------------- ### Execute ServiceNow GraphQL Queries - PowerShell Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Executes GraphQL queries against ServiceNow instances that have the GraphQL API enabled. Requires establishing a GraphQL-enabled session first. ```powershell # Create GraphQL-enabled session New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $cred -GraphQL # Execute GraphQL query $query = @" { incident(filter: {state: {equals: "1"}}) { number short_description priority assigned_to { name email } } } "@ $result = Invoke-ServiceNowGraphQL -Query $query ``` -------------------------------- ### Retrieve ServiceNow Incident by Description Source: https://github.com/snow-shell/servicenow-powershell/blob/master/Readme.md Fetches an incident record from ServiceNow that contains specific text ('powershell') in its description field. This cmdlet is useful for finding incidents based on descriptive content. Assumes an active ServiceNow session. ```powershell Get-ServiceNowRecord -Table incident -Description 'powershell' ``` -------------------------------- ### New-ServiceNowSession - Session Creation Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Creates an authenticated session to a ServiceNow instance. Supports basic authentication and OAuth 2.0 with automatic token refresh. The session is stored and used automatically by other cmdlets. ```APIDOC ## New-ServiceNowSession ### Description Creates an authenticated session to a ServiceNow instance using basic authentication or OAuth 2.0 with automatic access token refresh. The session is stored in a script-scoped variable and used automatically by all other cmdlets. ### Method Cmdlet ### Parameters #### Path Parameters None #### Query Parameters - **Url** (string) - Required - The base URL of the ServiceNow instance (e.g., 'myinstance.service-now.com'). - **Credential** (PSCredential) - Optional - A PSCredential object for basic authentication. If using OAuth, this is for the user. - **ClientCredential** (PSCredential) - Optional - A PSCredential object for OAuth 2.0 client credentials, where username is the Client ID and password is the Client Secret. - **Proxy** (string) - Optional - The URL of a proxy server to use for the connection. - **ProxyCredential** (PSCredential) - Optional - A PSCredential object for authenticating with the proxy server. - **TimeoutSec** (int) - Optional - The timeout in seconds for the session request. Defaults to 100. - **AccessToken** (string) - Optional - A pre-generated access token for authentication. - **ApiVersion** (int) - Optional - Specifies the API version to use (e.g., 1 or 2). - **PassThru** (switch) - Optional - Returns the session object if specified. ### Request Example ```powershell # Basic authentication session $credential = Get-Credential New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential # OAuth 2.0 authentication with automatic token refresh $userCred = Get-Credential -Message "Enter ServiceNow username and password" $clientCred = Get-Credential -Message "Enter OAuth Client ID as username and Client Secret as password" New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $userCred -ClientCredential $clientCred # Session with proxy and custom timeout $proxyCred = Get-Credential -Message "Proxy credentials" New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential -Proxy 'http://proxy.company.com:8080' -ProxyCredential $proxyCred -TimeoutSec 300 # Using pre-generated access token New-ServiceNowSession -Url 'myinstance.service-now.com' -AccessToken 'a9f8h34kjh5g43kj5h34g5k3j4h5g34' # Multiple sessions with PassThru for different API versions $sessionV1 = New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential -ApiVersion 1 -PassThru $sessionV2 = New-ServiceNowSession -Url 'myinstance.service-now.com' -Credential $credential -ApiVersion 2 -PassThru Get-ServiceNowRecord -Table incident -ID 'INC0010001' -ServiceNowSession $sessionV1 ``` ### Response #### Success Response (200) - **Session Object** - If -PassThru is specified, returns an object representing the authenticated session. #### Response Example (No direct JSON response for session creation, successful execution implies session is ready.) ``` -------------------------------- ### New-ServiceNowRecord - Generic Record Creation Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Creates records in any ServiceNow table by specifying the table name and a hashtable of field values. Supports passing through the created record. ```APIDOC ## New-ServiceNowRecord - Generic Record Creation ### Description Creates records in any ServiceNow table with flexible field specification through the Values parameter. ### Method ```powershell New-ServiceNowRecord ``` ### Parameters #### Path Parameters None #### Query Parameters - **Table** (string) - Required - The name of the ServiceNow table to create the record in. - **Values** (hashtable) - Required - A hashtable where keys are field names and values are the data for those fields. - **PassThru** (switch) - Optional - If specified, the cmdlet will output the created record. ### Request Example ```powershell # Create incident using generic function $values = @{ caller_id = 'john.doe' short_description = 'Printer not working' description = 'Office printer 3rd floor not responding' category = 'Hardware' urgency = 3 impact = 3 } New-ServiceNowRecord -Table incident -Values $values -PassThru # Create custom table record $customValues = @{ u_application_name = 'HR Portal' u_owner = 'jane.smith' u_environment = 'Production' u_status = 'Active' } New-ServiceNowRecord -Table 'u_custom_app_registry' -Values $customValues # Create configuration item $ciValues = @{ name = 'WEB-SERVER-05' asset_tag = 'IT-2025-0045' serial_number = 'SN123456789' model_id = 'Dell PowerEdge R740' assigned_to = 'datacenter.team' location = 'Building A - Datacenter' } New-ServiceNowRecord -Table cmdb_ci_server -Values $ciValues -PassThru # Create knowledge article $kbValues = @{ short_description = 'How to reset password' text = '

Password Reset Process

Follow these steps...

' kb_category = 'Self Service' workflow_state = 'draft' } New-ServiceNowRecord -Table kb_knowledge -Values $kbValues -PassThru ``` ### Response #### Success Response (200) - **sys_id** (string) - The unique identifier of the created record. - **number** (string) - The record number (if applicable). #### Response Example ```json { "sys_id": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", "number": "INC0010001" } ``` ``` -------------------------------- ### Build ServiceNow Queries - PowerShell Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Constructs encoded query strings for ServiceNow API requests using PowerShell-style operators. Supports simple and complex filters, sorting, and date range queries. ```powershell # Simple query $query = New-ServiceNowQuery -Filter @('state', '-eq', '1') # Complex query with multiple conditions $filter = @('state', '-eq', '1'), '-and', @('priority', '-in', '1,2'), '-or', @('assigned_to.name', '-like', 'admin') $query = New-ServiceNowQuery -Filter $filter # Query with sorting $query = New-ServiceNowQuery -Filter @('opened_at', '-ge', (Get-Date).AddDays(-30)) -Sort @('priority', 'asc'), @('opened_at', 'desc') # Date range query $filter = @('sys_created_on', '-between', (Get-Date).AddMonths(-6), (Get-Date)) $query = New-ServiceNowQuery -Filter $filter # Use query with Invoke-ServiceNowRestMethod for custom requests $queryString = New-ServiceNowQuery -Filter @('active', '-eq', 'true') ``` -------------------------------- ### Retrieve ServiceNow Attachment Metadata (PowerShell) Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt This snippet shows how to use the Get-ServiceNowAttachment cmdlet to retrieve information about attachments in ServiceNow. It covers fetching all attachments for a record, searching by file name, content type, size, and creation date, and retrieving recent attachments. ```powershell # Get all attachments for a specific record Get-ServiceNowAttachment -Id 'INC0010001' # Get attachments by table and record sys_id Get-ServiceNowAttachment -Table incident -Id 'a9b8c7d6e5f4a3b2c1d0e9f8a7b6c5d4' # Search all attachments by file name Get-ServiceNowAttachment -Table sys_attachment -Filter @('file_name', '-like', 'report') # Get attachments by content type Get-ServiceNowAttachment -Table sys_attachment -Filter @('content_type', '-eq', 'application/pdf') # Get large attachments Get-ServiceNowAttachment -Table sys_attachment -Filter @('size_bytes', '-gt', 1048576) -Sort @('size_bytes', 'desc') # Get recent attachments across all records Get-ServiceNowAttachment -Table sys_attachment -Filter @('sys_created_on', '-ge', (Get-Date).AddDays(-7)) -Sort @('sys_created_on', 'desc') -First 50 ``` -------------------------------- ### Retrieve ServiceNow Records with Get-ServiceNowRecord (PowerShell) Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Retrieves records from any ServiceNow table, supporting advanced filtering, sorting, paging, and custom variables. It allows querying by record ID, using PowerShell-style comparison operators or direct filter strings. Can fetch specific properties and raw values, and retrieve related child records. ```powershell # Get single record by number (prefix lookup automatic) Get-ServiceNowRecord -Id 'INC0010001' gsnr 'RITM0050032' # Using alias # Get incidents with complex filtering $filter = @('state', '-eq', '1'), '-and', @('short_description', '-like', 'powershell'), '-group', @('priority', '-eq', '1') Get-ServiceNowRecord -Table incident -Filter $filter -Sort @('opened_at', 'desc') # Date-based filtering for change requests opened in last 30 days Get-ServiceNowRecord -Table 'change_request' -Filter @('opened_at', '-ge', (Get-Date).AddDays(-30)) -IncludeTotalCount # Using filter string from ServiceNow UI (right-click filter > Copy query) Get-ServiceNowRecord -Table 'incident' -FilterString 'active=true^state=1^assigned_to.name=John Doe' # Get specific properties only Get-ServiceNowRecord -Id 'INC0010001' -Property 'short_description', 'sys_id', 'state', 'priority' # Get sys_id as raw value $sysId = Get-ServiceNowRecord -Table 'incident' -Filter @('number', '-eq', 'INC0010001') -Property sys_id -AsValue # Paging through large result sets Get-ServiceNowRecord -Table incident -First 100 -Skip 0 -IncludeTotalCount | ForEach-Object { Write-Host "$($_.number): $($_.short_description)" } # Get requested item with custom variables (form values) $ritm = Get-ServiceNowRecord -Id 'RITM0010001' -IncludeCustomVariable $ritm.CustomVariable.request_type.Value $ritm.CustomVariable.business_justification.DisplayName # Get all tasks (catalog tasks, change tasks, etc) for a parent record Get-ServiceNowRecord -ParentId 'RITM0010001' # Get specific task type for parent Get-ServiceNowRecord -Table 'catalog task' -ParentId 'RITM0010001' # Search by description field (varies by table) Get-ServiceNowRecord -Table user -Description 'John Smith' ``` -------------------------------- ### Export Attachments from ServiceNow - PowerShell Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Downloads attachment files from ServiceNow to the local filesystem or returns content as a byte array. Supports filtering and exporting specific attachments by SysID or from a record. ```powershell $attachments = Get-ServiceNowAttachment -Table sys_attachment -Filter @('file_name', '-endswith', '.log') $attachments | ForEach-Object { Export-ServiceNowAttachment -SysId $_.sys_id -Path "C:\Exports\$($_.file_name)" } ``` ```powershell # Export single attachment by sys_id Export-ServiceNowAttachment -SysId '1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d' -Path 'C:\Downloads\document.pdf' # Export all attachments from a record $attachments = Get-ServiceNowAttachment -Id 'INC0010001' foreach ($attachment in $attachments) { Export-ServiceNowAttachment -SysId $attachment.sys_id -Path "C:\Downloads\INC0010001_$($attachment.file_name)" } # Export and process in memory $content = Export-ServiceNowAttachment -SysId '9f8e7d6c5b4a3928190a8b7c6d5e4f3a' -AsValue $text = [System.Text.Encoding]::UTF8.GetString($content) $text | Out-File 'C:\Temp\processed.txt' # Bulk export with filtering Get-ServiceNowAttachment -Table sys_attachment -Filter @('content_type', '-eq', 'image/png') | ForEach-Object { Export-ServiceNowAttachment -SysId $_.sys_id -Path "C:\Images\$($_.file_name)" } # Export with error handling try { Export-ServiceNowAttachment -SysId $attachmentId -Path $outputPath Write-Host "Successfully exported to $outputPath" } catch { Write-Error "Failed to export attachment: $_" } ``` -------------------------------- ### Export ServiceNow Records to Various Formats - PowerShell Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Exports ServiceNow records to CSV, XLS, XLSX, XML, or PDF formats. Supports extensive filtering, sorting, and selection of specific properties for the export. ```powershell # Export incidents to CSV Export-ServiceNowRecord -Table incident -Filter @('state', '-eq', '1') -Path 'C:\Reports\open_incidents.csv' # Export to Excel with specific properties Export-ServiceNowRecord -Table incident -Property 'number', 'short_description', 'priority', 'assigned_to', 'opened_at' -Path 'C:\Reports\incidents.xlsx' # Export change requests to PDF Export-ServiceNowRecord -Table change_request -Filter @('state', '-in', '1,2,3') -Sort @('risk', 'desc') -Path 'C:\Reports\active_changes.pdf' # Export with date filtering $filter = @('closed_at', '-between', (Get-Date '2025-01-01'), (Get-Date '2025-12-31')) Export-ServiceNowRecord -Table incident -Filter $filter -Path 'C:\Reports\2025_incidents.xlsx' # Export filtered results with description search Export-ServiceNowRecord -Table incident -Description 'network' -Filter @('priority', '-eq', '1') -Path 'C:\Reports\critical_network_incidents.csv' ``` -------------------------------- ### Update ServiceNow Record Fields Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Demonstrates updating ServiceNow records using the Update-ServiceNowRecord cmdlet. Supports updates by record number or sys_id, including custom variables. It handles pipeline input, bulk updates with array values, and returns the modified record using PassThru. ```powershell # Update by record number (table auto-detected from prefix) Update-ServiceNowRecord -ID 'INC0010001' -InputData @{ state = 'In Progress' assigned_to = 'john.doe' work_notes = 'Investigation started' } # Update with table name and sys_id for better performance Update-ServiceNowRecord -Table incident -ID '13378afb97a6451ab1ec2c9e85313188' -InputData @{ state = 'Resolved' close_notes = 'Issue resolved by restarting service' close_code = 'Solved (Permanently)' } # Pipeline update from query results Get-ServiceNowRecord -Table incident -Filter @('assigned_to', '-eq', 'old.user') | Update-ServiceNowRecord -InputData @{'assigned_to' = 'new.user'} # Update custom variables (RITM form fields) Update-ServiceNowRecord -ID 'RITM0010001' -CustomVariableData @{ 'approval_required' = 'Yes' 'cost_center' = 'IT-Operations' } # Update both standard fields and custom variables Update-ServiceNowRecord -ID 'RITM0050003' ` -InputData @{'state' = '3'; 'comments' = 'Processing request'} ` -CustomVariableData @{'delivery_date' = '2025-12-15'} ` -PassThru # Bulk update with array values (comma-separated) Update-ServiceNowRecord -ID 'CHG0010001' -InputData @{ watch_list = @('user1', 'user2', 'user3') work_notes = 'Added additional reviewers' } # Update and return modified record $updated = Update-ServiceNowRecord -ID 'INC0010002' -InputData @{state = '6'} -PassThru Write-Host "Incident $($updated.number) closed at $($updated.closed_at)" ``` -------------------------------- ### Add-ServiceNowAttachment - Upload Files Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Attaches files to ServiceNow records. It supports specifying the record by ID or by table and sys_id, allows multiple file attachments, and can auto-detect MIME types. The `PassThru` parameter can return details of the uploaded file. ```APIDOC ## Add-ServiceNowAttachment - Upload Files ### Description Attaches files to ServiceNow records with automatic MIME type detection and support for multiple files. ### Method ```powershell Add-ServiceNowAttachment ``` ### Parameters #### Path Parameters None #### Query Parameters - **Id** (string) - Required - The record number or sys_id of the ServiceNow record to attach the file to. - **Table** (string) - Optional - The name of the ServiceNow table if the `Id` parameter refers to a sys_id and not a record number. - **File** (string or string[]) - Required - The path to the file or an array of paths to files to be attached. - **ContentType** (string) - Optional - Explicitly set the MIME type of the attachment. If not provided, it's auto-detected. - **PassThru** (switch) - Optional - If specified, the cmdlet will output an object containing details of the uploaded attachment. ### Request Example ```powershell # Add single attachment by record number Add-ServiceNowAttachment -Id 'INC0010001' -File 'C:\Logs\error_log.txt' # Add multiple attachments Add-ServiceNowAttachment -Id 'CHG0010002' -File @('C:\Docs\plan.pdf', 'C:\Docs\approval.pdf') # Add with explicit table and sys_id Add-ServiceNowAttachment -Table incident -Id '8e7f9a1b2c3d4e5f6a7b8c9d0e1f2a3b' -File 'C:\Screenshots\error.png' # Override content type Add-ServiceNowAttachment -Id 'INC0010003' -File 'C:\Data\export.dat' -ContentType 'application/octet-stream' # Add attachment and get file details back $attachment = Add-ServiceNowAttachment -Id 'RITM0010001' -File 'C:\Forms\request_form.pdf' -PassThru Write-Host "Uploaded: $($attachment.file_name), Size: $($attachment.size_bytes) bytes" # Pipeline from record creation $incident = New-ServiceNowIncident -Caller 'user1' -ShortDescription 'Issue report' -PassThru $incident | Add-ServiceNowAttachment -File 'C:\Reports\diagnostic_report.html' # Add attachments to multiple records Get-ServiceNowRecord -Table incident -Filter @('assigned_to', '-eq', 'admin'), '-and', @('state', '-eq', '2') | Add-ServiceNowAttachment -File 'C:\Updates\status_update.pdf' ``` ### Response #### Success Response (200) - **file_name** (string) - The name of the uploaded file. - **size_bytes** (integer) - The size of the uploaded file in bytes. - **content_type** (string) - The MIME type of the uploaded file. - **sys_id** (string) - The sys_id of the attachment record in ServiceNow. #### Response Example ```json { "file_name": "request_form.pdf", "size_bytes": 153600, "content_type": "application/pdf", "sys_id": "f1e2d3c4b5a607b8c9d0e1f2a3b4c5d6" } ``` ``` -------------------------------- ### Get-ServiceNowRecord - Record Retrieval Source: https://context7.com/snow-shell/servicenow-powershell/llms.txt Retrieves records from any ServiceNow table with advanced filtering, sorting, paging, and custom variable support. Supports PowerShell-style comparison operators. ```APIDOC ## Get-ServiceNowRecord ### Description Retrieves records from any ServiceNow table with advanced filtering, sorting, paging, and custom variable support. This is the primary function for querying ServiceNow data with PowerShell-style comparison operators. ### Method Cmdlet ### Endpoint (N/A - This is a cmdlet, not a direct REST endpoint call. It interfaces with the ServiceNow REST API.) ### Parameters #### Path Parameters None #### Query Parameters - **Table** (string) - Required - The name of the ServiceNow table to query (e.g., 'incident', 'change_request'). - **Id** (string) - Optional - The sys_id or record number of a specific record to retrieve. - **Filter** (array of objects/strings) - Optional - An array defining filter conditions using PowerShell-style comparison operators and logical connectors (e.g., @('state', '-eq', '1')). - **FilterString** (string) - Optional - A filter string directly from ServiceNow (e.g., 'active=true^state=1'). - **Sort** (array of strings) - Optional - An array specifying the field(s) to sort by and the direction (e.g., @('opened_at', 'desc')). - **First** (int) - Optional - The maximum number of records to return (for paging). - **Skip** (int) - Optional - The number of records to skip (for paging). - **Property** (array of strings) - Optional - A list of specific fields to retrieve for each record. - **AsValue** (switch) - Optional - Returns only the value of the specified property (typically used with -Property and a single property). - **IncludeTotalCount** (switch) - Optional - Includes the total count of records matching the query in the result. - **IncludeCustomVariable** (switch) - Optional - Includes custom variables (form values) for RITM records. - **ParentId** (string) - Optional - Retrieves records associated with a parent record's sys_id. - **Description** (string) - Optional - A search term to use for searching within the description field (behavior may vary by table). - **ServiceNowSession** (object) - Optional - A ServiceNow session object created by `New-ServiceNowSession`. If not provided, the cmdlet will attempt to use the default session. ### Request Example ```powershell # Get single record by number (prefix lookup automatic) Get-ServiceNowRecord -Id 'INC0010001' gsnr 'RITM0050032' # Using alias # Get incidents with complex filtering $filter = @('state', '-eq', '1'), '-and', @('short_description', '-like', 'powershell'), '-group', @('priority', '-eq', '1') Get-ServiceNowRecord -Table incident -Filter $filter -Sort @('opened_at', 'desc') # Date-based filtering for change requests opened in last 30 days Get-ServiceNowRecord -Table 'change_request' -Filter @('opened_at', '-ge', (Get-Date).AddDays(-30)) -IncludeTotalCount # Using filter string from ServiceNow UI (right-click filter > Copy query) Get-ServiceNowRecord -Table 'incident' -FilterString 'active=true^state=1^assigned_to.name=John Doe' # Get specific properties only Get-ServiceNowRecord -Id 'INC0010001' -Property 'short_description', 'sys_id', 'state', 'priority' # Get sys_id as raw value $sysId = Get-ServiceNowRecord -Table 'incident' -Filter @('number', '-eq', 'INC0010001') -Property sys_id -AsValue # Paging through large result sets Get-ServiceNowRecord -Table incident -First 100 -Skip 0 -IncludeTotalCount | ForEach-Object { Write-Host "$($_.number): $($_.short_description)" } # Get requested item with custom variables (form values) $ritm = Get-ServiceNowRecord -Id 'RITM0010001' -IncludeCustomVariable $ritm.CustomVariable.request_type.Value $ritm.CustomVariable.business_justification.DisplayName # Get all tasks (catalog tasks, change tasks, etc) for a parent record Get-ServiceNowRecord -ParentId 'RITM0010001' # Get specific task type for parent Get-ServiceNowRecord -Table 'catalog task' -ParentId 'RITM0010001' # Search by description field (varies by table) Get-ServiceNowRecord -Table user -Description 'John Smith' ``` ### Response #### Success Response (200) - **Array of Objects** - Each object represents a record from the specified ServiceNow table, containing the retrieved fields. - **TotalCount** (int) - Included if `-IncludeTotalCount` is used. - **CustomVariable** (object) - Included if `-IncludeCustomVariable` is used for RITM records. #### Response Example ```json [ { "sys_id": "a1b2c3d4e5f678901234567890abcdef", "number": "INC0010001", "short_description": "Server is down", "state": "1", "priority": "1", "opened_at": "2023-10-27 10:00:00", "sys_class_name": "incident" }, { "sys_id": "b2c3d4e5f678901234567890abcdefa1", "number": "INC0010002", "short_description": "PowerShell script error", "state": "1", "priority": "2", "opened_at": "2023-10-27 11:30:00", "sys_class_name": "incident" } ] ``` ```