LogoLogo
LearnDocumentationSupportCommunity
Version 6.30
Version 6.30
  • Welcome
  • Nexthink V6
  • Overview
    • Software components
    • Collector
    • Finder
    • Engine
    • Portal
    • Nexthink Library
    • Digital Experience Score
  • Installation and configuration
    • Planning your installation
      • Overview of the installation process
      • Hardware requirements
      • Connectivity requirements
      • Software requirements
      • Reference architectures
    • Installing Portal and Engine Appliances
      • Installing the Appliance
      • Installing the Appliance on Azure
      • Installing the Appliance on AWS
      • Installing the Appliance on OTC
      • Managing Appliance accounts
      • Setting the names of the Portal
      • Setting the names of the Engines
      • Specifying your internal networks and domains
      • Federating your Appliances
      • STIG compliance in Web Console
      • Connecting the Portal to the Engines
      • Configuring session performance storage
      • Configuring device performance storage
      • Setting up a software license
      • Sending email notifications from the Appliance
      • Allocating resources for the Portal
    • Installing the Collector
      • Installing the Collector on Windows
      • Installing the Collector on macOS
      • Installing the Collector for a Proof of Value
      • Assigning Collectors to Engines
      • Assignment of roaming Collectors
      • Collector MSI parameters reference table
      • Nxtcfg - Collector configuration tool
      • Inspecting the connection status of the Collector
      • Querying the status of the TCP connection of the Collector
      • Reporting the URL of HTTP web requests
      • Auditing logon events
      • Viewing user interactions in virtualized and embedded environments
      • Engage notifications on macOS
      • Configuring Collector level anonymization
    • Collector remote connectivity
      • Redirecting and anonymizing Collector traffic
      • Redirecting the Collector TCP channel
      • Support for DirectAccess
      • Windows Collector proxy support
      • Mac Collector proxy support
    • Installing the Event Connector
      • Installing the Event Connector on Linux
    • Installing the Finder
      • Installing the Finder on Windows
      • Enabling Cross-Engine Finder features
      • Expanding the time frame of investigations in the Finder
      • Enabling Finder access to the Library
      • Finder proxy support
    • Updating from V6.x
      • Updating the Appliance
      • Content centralization when updating the Appliance
      • Updating the Collector
      • Viewing Collector deprecated fields
      • Updating the Finder
    • Security and user account management
      • Importing and replacing certificates
      • Hierarchizing your infrastructure
      • Adding users
      • Enabling SAML authentication of users
      • Just-In-Time provisioning of user accounts
      • Enabling Windows authentication of users
      • Multi-factor authentication for local accounts overview
      • Provisioning user accounts from Active Directory
      • Establishing a privacy policy
      • Disabling local accounts for interactive users
      • Setting the complexity and minimum length of passwords for local accounts
      • Protecting local accounts against brute force attacks
      • Preventing password saving in the Finder
      • Controlling session timeouts in the Portal
      • Security settings in the Appliance
      • Setting the Do Not Disturb periods between campaigns
    • Data retrieval and storage
      • Data retention
      • Increasing the maximum number of metrics
      • Establishing a data retention policy in the Engine
      • Storing Engine data in a secondary disk drive
      • Importing data from Microsoft Active Directory
      • Setting the locale in the Portal
      • Changing the Time Zone of the Portal
      • Time Zones and data collection
      • Changing the data collection time of the Portal
      • Nightly task schedules timetable
      • Changing the thresholds of High CPU warnings
      • Automatic restart of unresponsive Engine
    • Maintenance operations
      • Logging in to the CLI
      • Special operation modes for the Engine and the Portal
      • Changing the default ports in the Appliance
      • Centralized Management of Appliances and Engines
      • Monitoring the performance of the Appliance
      • Resizing partitions in Appliance
      • Configuring the system log
      • Examining the logs in the Portal
      • GDPR - Retrieving or anonymizing personal data
      • Finding out unlicensed devices
      • Removing devices
      • Installing third-party software in the Appliance
      • Installing VMware Tools in the Appliance
      • Operational data sent to Nexthink
      • Sending additional data to Support
    • Disaster recovery
      • Planning for disaster recovery
      • Web Console backup and restore
      • Engine backup and restore
      • Portal backup and restore
      • Rule-based assignment backup and restore
      • License backup and restore
      • PKI backup and restore
    • Branding
      • Branding the Portal
      • Branding of campaigns
  • User manual
    • Getting started
      • Logging in to the Finder
      • Logging in to the Portal
      • Enabling STIG in Webconsole
    • Querying the system
      • Searching the subject of interest
      • Executing an investigation
      • Creating an investigation
      • Editing the options of an investigation
      • Combining logical conditions in investigations
      • Navigating through the results of an investigation
      • Properties of users and devices
    • Visualizing system activity in the Finder
      • Getting a quick overview
      • Graphically observing the activity of users and devices
      • Observing service performance
      • Viewing network connections
      • Viewing web requests
      • Viewing executions
    • Monitoring IT custom metrics
      • Creating a metric
      • Examples of metrics
      • Session performance
      • Device performance
      • Following the evolution of a metric
      • Finding the visuals of a metric
    • Monitoring IT services
      • Analyzing service quality
      • Creating a service
      • Following the evolution of a service
      • Specifying URL paths of web-based services
    • Engaging with the end user
      • Getting feedback from the end users
      • Types of campaigns
      • Creating a campaign
      • Editing a campaign
      • Types of questions
      • Controlling the flow of questions
      • Translating a campaign
      • Triggering a campaign manually
      • Limiting the reception rate of campaigns
      • Scrutinizing the results of a campaign
      • Continuously measuring the satisfaction of employees
    • Rating devices and users with scores
      • Computing scores
      • Creating a score
      • Checking and comparing ratings
      • Computing potential savings
      • Score XML Reference
      • Documenting scores
    • Remotely acting on devices
      • Scenarios for remote actions
      • Creating a remote action
      • Executing remote actions
      • Triggering a remote action manually
      • Writing scripts for remote actions on Windows
      • Writing scripts for remote actions on Mac
      • Example of self-healing scenario
      • Example of self-help scenario
      • Application control and remote actions
    • Organizing objects with categories
      • Classifying objects of the same type
      • Creating categories and keywords
      • Tagging objects manually
      • Tagging objects automatically
      • Importing tags from text files
    • Getting notified by the system
      • Receiving Engage campaigns
      • Receiving email digests
      • Receiving alerts
      • Creating a service-based alert
      • Creating an investigation-based alert
    • Building web-based dashboards
      • Introducing dashboards in the Portal
      • Creating a dashboard
      • Examining metrics in depth
      • Documenting dashboards
      • Assessing license use
      • Computing dashboard data
      • Reusing dashboard content
    • Importing and exporting authored content
      • Methods for reusing authored content
      • Manually sharing Finder content
      • Importing a content pack
      • Conflict resolution
      • Exporting a content pack
  • Library packs
    • Compliance
      • Device Compliance
    • Configuration Manuals
      • Overview (Configuration Manuals)
      • Installing A New Version Of A Library Pack
    • Digital Employee Score (DEX score)
      • DEX Score Installation And Configuration
      • Detailed Library Pack Changelog
    • Device management
      • Reduce logon duration
      • Group Policy Management
      • Hardware Asset Renewal
      • Hardware Asset Renewal Advanced
      • Application Auto-Start Impact
    • Remote Employee Experience
      • Remote Worker Experience
      • Home Networking
      • Change Log And Upgrade Process
      • Remote Worker Vs Office Worker Device Category
      • Remote Worker Insights
      • DEX V2 Upgrade Of Remote Worker
    • Persona Insight
      • Persona Insight - Overview
      • Persona Insight - Library Pack
      • Persona Insight - Score Only Pack
      • Persona Insight - Without Campaign pack
      • Persona Insight - Getting Started and Upgrade Procedure
      • Persona Insight - Configuration Guide
      • Persona Insight - Troubleshooting - Multiple devices on multiple engines
      • Persona Insight - Reference Guide
      • Persona Insight - Example Pack
      • Persona Insight - Device Sizing
        • Persona Insight - Device Sizing Overview
        • Persona Insight - Device Sizing Configuration
      • Persona Insight - Application Sizing
        • Persona Insight - Application Sizing Overview
        • Persona Insight - Application Sizing Configuration
      • Legacy Persona documentation
        • Persona Insight - Library Pack (V.1.0.0.0)
        • Persona Insight - Base Pack
        • Persona Insight - Base Pack Advanced
        • Persona Insight - Customization Guide (V1.0.0.0)
        • Persona Insight - Configuration Guide (V1.0.0.0)
        • Persona Insight - Reference Guide (V1.0.0.0)
    • GSuite
      • GSuite: Health
      • GSuite: Services
      • GSuite: Sentiment
      • GSuite: Advanced Health
    • Support
      • Support: Level 1
    • Shadow IT
      • Shadow IT
    • Malware Protection
      • Malware Protection
    • Office 365 Health
      • Office 365 Health: Overview
      • Office 365 Health: Services
    • Office 365 OneDrive
      • OneDrive Summary
      • OneDrive Operations
      • OneDrive Advanced Health
      • OneDrive Migration
      • OneDrive Sentiment
      • OneDrive Management
      • OneDrive Advanced Operations
    • Office 365 Teams
      • Teams Overall Configuration
      • Teams - Migration
      • Teams - Health
      • Teams - Advanced Health
      • Teams - Adoption
    • Microsoft 365 Apps
      • Microsoft 365 Apps - Operate
    • Employee Self Service
      • Overview
      • Configuration
      • Usage
    • Onboarding Experience Management
      • OEM - Overview
      • OEM - Configuration
    • Office 365 Outlook
      • Outlook Troubleshooting
    • Virtualization
      • Virtualization: Operate
      • Virtualization: AVD - Advanced
      • Virtualization: Citrix Advanced
      • Virtualization: Project
      • Virtualization: Troubleshooting
        • Virtualization: Troubleshooting: Configuration
    • Windows
      • Win10: Configuration
      • Win10: Migration
      • Win10: Feature Update
      • Win10: Quality Update
      • Windows Defender Management
      • Administrators Management
    • Windows 11
      • Windows 11 - Readiness
      • Windows 11 - Migration Pilot
      • Windows 11 - Migration
      • Windows 11 - Operate
    • Webex
      • Webex Operate
    • Zoom
      • Zoom Operate
    • Remote Actions
      • Get Performance Monitor Data
      • Skype For Business
      • Restart Device
      • Upload Logs to S3 using PreSigned URLs
    • Software Asset Optimization
    • Collaboration Optimization
      • Collaboration Optimization - Solution Overview
      • Collaboration Optimization - Configuration
      • Collaboration Optimization - Usage / Troubleshooting
    • Systems Management
      • Manage Configuration Drift
      • MS ConfigMgr - Client Health
        • MS ConfigMgr - Client Health - Summary
        • MS ConfigMgr - Client Health - Configuration Guide
      • Intune
        • Intune - Health
          • Intune - Health - Summary
          • Intune - Health - Configuration Guide
    • Return to the office
      • Return to the office - Planning
      • Return to the office - Readiness
    • Green IT
      • Green IT - Overview
      • Green IT - Configuration Guide
    • Hybrid Working
      • Hybrid Working Experience
      • Hybrid Working Experience - Installation and upgrade procedure
  • Integrations
    • Nexthink ServiceNow Service Graph Connector
      • Overview
        • Roles and Permissions
        • Modules
      • Installation and Configuration Guide
        • Pre-requisites
          • Configure Identification Rules
          • Import and setup the CMDB categories in Finder
        • Setup
          • Configure the connection
          • Configure import properties
          • Configure additional engines
          • Set up scheduled import jobs
      • Data transformation and mapping by default
      • How to customize the behaviour of the Connector
      • FAQ
        • Why ServiceNow Service Graph Connector?
        • What about Nexthink CMDB Connector?
        • Why is the name the primary key for the devices?
      • Troubleshooting
        • IRE identification issues
          • [No Choice found in the sys_choice table for the target table](integrations/nexthink-servicenow-service-graph-connector/troubleshooting/ire-identification-issues/ no-choice-found-in-the-sys_choice-table-for-the-target-table.md)
          • Identification rules not created
          • Discovery_source choice not created
        • Timeout Errors
          • ECCResponseTimeoutException
          • HTTP 0 error
        • MID server issues
          • java.lang.NullPointerException
          • MID Server memory issues
          • Not trusted certificates in Quebec release
        • Configure credentials issues
          • [Not allowing update of property authentication_choice](integrations/nexthink-servicenow-service-graph-connector/troubleshooting/configure-credentials-issues/ not-allowing-update-of-property-authentication_choice.md)
          • Invalid username/password combo (HTTP 401/403)
        • Configure Engines Issues
          • [The client secret supplied for a confidential client is invalid](integrations/nexthink-servicenow-service-graph-connector/troubleshooting/configure-engines-issues/ the-client-secret-supplied-for-a-confidential-client-is-invalid.md)
        • No Cis imported and no errors found in the log
    • Nexthink ServiceNow Incident Management Connector (IMC)
      • Installation and configuration guide (IMC)
      • Troubleshooting Guide (IMC)
      • Domain separation installation (IMC)
    • Nexthink ServiceNow CMDB Connectors
      • Installation and Configuration Guide
      • Troubleshooting Guide
      • Field transformation and normalisation examples
    • Nexthink Event Connector
      • High level overview
      • Installation and Configuration Guide
      • Troubleshooting guide
      • RPM installation
      • Splunk specific documentation
        • Upgrading from Splunk Connector to Event Connector
        • Splunk add-on installation and usage
    • Nexthink Chatbot SDK
      • Introduction and concepts
      • Installation, configuration and update guide
        • Installation and configuration
        • Update to newer version
        • Uninstallation
        • Authentication
        • Topics configuration
        • Remote action configuration
        • Advanced configuration
        • Additional resources and references
      • Dimensioning guide
      • Troubleshooting
      • Technical solution description
      • Downloads and release notes
  • Glossary and references
    • Search and information display
      • Search in Finder
      • Keyboard shortcuts for column display selection
      • Campaign display compatibility
      • Real-time and consolidated service data
      • Service errors and warnings
      • Errors and warnings for devices and executions
      • Types of widgets
      • Widget compute state in charts
      • Errors in the execution of remote actions
      • Top results of Cross-Engine investigations
      • Engine data history
    • Tooltips in the user and device views
      • Alerts tooltips
      • Warnings tooltips
      • Errors tooltips
      • Activity tooltips
      • Services tooltips
    • Database information and organization
      • Maximum supported values
      • Local and shared content
      • Device Identification
      • Local IP address of devices
      • Timestamping of events
      • Boot and logon duration
      • Application startup duration
      • Application not responding events
      • Memory and CPU usage
      • Status of TCP connections
      • Status of UDP connections
      • Network and port scan conditions
      • Binary paths
      • Maximum number of Binaries
      • Package Executable Mapping
      • Metro apps
      • Investigation with packages
      • Portal aggregation and grouping
      • Focus time metric
    • Security
      • Access rights and permissions
      • Active Directory authentication
      • Canonical domain names for Windows authentication
      • System alerts
      • Audit trail
      • Appliance hardening
      • STIG hardening
      • FIPS 140-2 compliance
      • Security bulletins
        • Is Nexthink affected by Okta breach
        • Is Nexthink affected by SolarWinds breach
        • Nexthink and Log4j - Security bulletin
        • CVE-2022-22965 - Security Vulnerability Spring4shell - Spring Framework
        • Version 6.22.2.10: Security Vulnerability Maintenance Release
        • The Collector V6.27.X Release – Security Bulletin
    • References
      • Components of the Collector
      • Server support
      • Compatibility mode
    • Glossary
      • Activity
      • Alert
      • Application
      • Binary
      • Campaign
      • Category
      • Connection
      • Dashboard
      • Destination
      • Device
      • Domain
      • Entity
      • Event
      • Executable
      • Execution
      • Focus time
      • Hierarchy
      • Installation
      • Investigation
      • Keyword
      • Metric
      • Module
      • Object
      • Package
      • Platform
      • Port
      • Printer
      • Score
      • Service
      • Session
      • System boot
      • User
      • User logon
      • Web request
      • Widget
  • API and integrations
    • Integrating with Nexthink
      • Event Connector
      • Getting data through the NXQL API
      • Bidirectional integration with the Finder
      • Count metrics API
      • Software metering API
      • Services API
      • List Engines API
      • GetSID API
      • Triggering campaigns via their API
      • Triggering remote actions via their API
      • Audit trail API
      • Integrating investigation-based alerts
      • Downloads
    • NXQL API
      • Introducing the NXQL API
      • NXQL Tutorial
      • NXQL language definition
      • NXQL Data Model
    • Integrations
      • Excel integration with NXQL
      • Power BI
      • Azure Data Lake Storage Gen2
      • Splunk Event Connector
    • ServiceNow
      • CMDB Connector
      • Incident Management Connector
      • Event Management

© Nexthink

  • Privacy policy
  • Responsible Disclosure Policy
On this page
  • Overview
  • Encoding
  • Signing your own scripts
  • Writing generic scripts
  • Output variables
  • Interacting with end-users in self-help scenarios
  • Obtaining the UID of a campaign
  • Running a campaign from the script of a remote action
  • Example code
  • Error handling
  • Performance measurement

Was this helpful?

  1. User manual
  2. Remotely acting on devices

Writing scripts for remote actions on Windows

Last updated 2 months ago

Was this helpful?

Overview

The payload of remote actions on Windows are PowerShell scripts that run on the devices of the employees. PowerShell is a scripting language from Microsoft that is suited for task automation and configuration management and it is built on top of the .NET Framework in Windows devices. PowerShell is therefore ideal to get on-demand data from devices, perform self-healing tasks, or modifying the configuration of a device, which are typical use cases for remote actions.

Learn here the specifics of how to write PowerShell scripts for remote actions. This article assumes familiarity of the reader with PowerShell scripting.

Find more information about writing scripts for remote actions:

Applies to platform | Windows |

Encoding

To write your own PowerShell scripts for remote actions, encode the files that hold the text of your scripts in UTF-8 with BOM. The BOM (Byte Order Mark) is a Unicode character that must be present at the beginning of the file and whose representation in UTF-8 documents is the following sequence of three bytes (in hexadecimal): EF BB BF.

End each line in the code with the usual character sequence in Windows systems: CR+LF.

Failing to provide the right encoding to your script files will result in the inability of remote actions to run on the devices of the end-users.

Signing your own scripts

For security reasons, Nexthink strongly recommends that you sign all the scripts that you write. Unsigned scripts are only suitable for testing in pre-production environments.

To sign your PowerShell scripts, use the command as follows:

  1. Get your code-signing certificate (assuming you have one), either

$cert = Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert

  • From a PFX file:

$cert = Get-PfxCertificate -FilePath C:\Test\Mysign.pfx

2. Sign your script for remote actions (e.g. remoteaction.ps1) with the code-signing certificate, adding a timestamp to keep it working after certificate expiration (the example code below uses the DigiCert timestamp server):

Set-AuthenticodeSignature -FilePath .\remoteaction.ps1 -Certificate $cert -IncludeChain All -TimestampServer "http://timestamp.digicert.com"

3.Optional: Verify the signature in the script.

Get-AuthenticodeSignature .\remoteaction.ps1 -Verbose | fl

Writing generic scripts

Scripts may be written in a generic way so they can be adapted to particular use cases. To make your script generic, declare formal parameters at the beginning of the PowerShell script. Provide actual values to the parameters in the Finder, when editing the remote action that holds the script.

Genericity is specially useful in the case of digitally signed scripts that require some customization. When a script is signed, any modification to its text content breaks the signature. By making a signed script generic, you allow its customization via parameters. With parameters, the text of the script remains unchanged and thus the digital signature remains valid. The values for the parameters that a remote action passes to the script determine its actual behavior.

For example, to make a script that reads from a registry key generic, declare a parameter in the script that holds the path to the key in the registry. In this way, several remote actions may use the same script to read from different registry keys by supplying a different path to the parameter in the script.

Declare parameters at the beginning of a script in the usual way for PowerShell scripts:

param(
    [string]$filePath,
    [string]$regPath
)

The editor of remote actions recognizes the parameters of any imported PowerShell script and lists them in the Parameters section, below the script text. Provide actual values to the parameters in the text input boxes displayed to the right of each parameter name. Note that the actual values are always passed to the script as text: if the script declares parameters whose type is other than the string type, ensure that the values that you provide can be properly converted to the type of their corresponding parameter.

Output variables

The execution of a script may generate some outputs that you want to store as on-demand data in the Engine. To that end, Nexthink provides a .NET assembly (nxtremoteactions.dll) that is installed in the device of the end-user at the same time as the Collector. The assembly includes a class called Nxt that provides the methods to write results to the Engine.

To use the Nxt class, add the following line at the beginning of a PowerShell script for remote actions:

Add-Type -Path $env:NEXTHINK\RemoteActions\nxtremoteactions.dll

Use the methods of the class to write the desired outputs. All write methods accept two arguments: the name of the output and the value to write. For instance, to write the size of a file to the Engine:

[Nxt]::WriteOutputSize("FileSize", $fileSize)

The editor of remote actions recognizes the calls to write outputs in the script and lists the output variables under the Outputs section below the script text. Set the label of the output to indicate how to refer to it in investigations and metrics.

The ending of each write method indicates the type of the output. Find the list of available methods and the corresponding PowerShell type of the value to be written in the table below:

Nxt write method
PowerShell type
Constraints

WriteOutputString

[string]

0 - 1024 characters (output truncated if bigger)

WriteOutputBool

[bool]

true / false

WriteOutputUInt32

[uint32]

  • Min: 0

  • Max: 4 294 967 295

WriteOutputFloat

[float]

  • Min: -3.4E+38

  • Max: 3.4E+38

WriteOutputSize

[float]

  • Min: 0

  • Max: 3.4E+38

WriteOutputRatio

[float]

WriteOutputBitRate

[float]

WriteOutputDateTime

[DateTime]

DD.MM.YYYY@HH:MM

WriteOutputDuration

[TimeSpan]

  • Min: 0 ms

  • Max: 49 days

  • Precision in milliseconds

WriteOutputStringList

[string[]]

Same as string

Interacting with end-users in self-help scenarios

To help end-users solve issues by themselves, combine remote actions with campaigns. In combination with remote actions, campaigns let you inform end-users about the detection of an issue and guide them through its resolution.

Because self-help scenarios make use of remote actions and campaigns, they require the purchase of both the Nexthink Act and the Nexthink Engage products.

To display a campaign in the desktop of an end-user that is interacting with a device:

  • The campaign must target users with a remote action and be published.

  • The script of the remote action can be executed either:

    • In the context of the end-user, if the action does not need any special privileges.

    • In the context of the local system account, if the action needs administrative privileges.

Obtaining the UID of a campaign

The methods to run a campaign from a remote action that are detailed in the section below require the UID of the campaign to be passed as an argument. Thus, to run a campaign from a remote action, first you need to get the UID of the campaign.

To pass this UID to a remote action, it is convenient to declare a parameter in the script of the remote action for each campaign that it has to run and use the UID as the actual value for the parameter when editing the remote action.

To get the UID of a campaign and pass it to a remote action as a parameter:

  1. Log in to the Finder as a user with the right to edit campaigns and remote actions.

  2. In the Campaigns section of the left-hand side accordion, right-click the name of a campaign that you wish to launch from a remote action.

  3. Select Export > Campaign Uid to clipboard to copy the UID of the campaign.

  4. In the Remote actions section of the left-hand side accordion, double-click the name of the remote action that should run the campaign to edit it. The remote action should include a script that declares parameters for storing the UID of the campaign.

  5. In the Parameters section under the script, select the parameter that should hold the UID of the campaign.

  6. Press Ctrl+V to paste the actual UID of the campaign and assign it to the corresponding parameter.

Running a campaign from the script of a remote action

To interact with campaigns from a remote action, the script of the remote action requires to load a .NET assembly (nxtcampaignaction.dll) that is installed in the device of the end-user along with the Collector. The assembly includes the class Nxt.CampaignAction that provides the methods to control the execution of a campaign and get the responses from the user.

To load the assembly, add the following line at the beginning of the script:

Add-Type -Path $env:NEXTHINK\RemoteActions\nxtcampaignaction.dll

The methods of Nxt.CampaignAction to control campaigns are the following:

NxTrayResp RunCampaign(string campaignUid)

Run the campaign identified by the campaignUid and block until the user finishes answering. Return the response in an object of type NxTrayResp.

NxTrayResp RunCampaign(string campaignUid, int timeout)

Run the campaign identified by the campaignUid and block until the user finishes answering or after the specified timeout (in seconds) elapses. Return the response in an object of type NxTrayResp.

RunStandAloneCampaign(string campaignUid)

Run the campaign identified by the campaignUid without blocking nor expecting results.

String GetResponseStatus(NxTrayResp response)

Given a response object of type NxTrayResp, the method returns a string that reflects the status of the campaign. Possible values for the status:

  • fully, the user has fully answered the questions of the campaign.

  • declined, the user declined to participate in the campaign.

  • postponed, the user accepted to participate in the campaign.

  • timeout, the campaign was timed out before the user finished answering.

  • connectionfailed, the script was unable to connect to the Collector component that controls campaign notifications.

  • notificationfailed, the script was unable to notify the Collector component that controls campaign notifications.

string[] GetResponseAnswer(NxTrayResp response, string questionLabel)

Given a response object of type NxTrayResp and the label that identifies a question in the campaign, the method returns the response given by the user.

  • In the case of a single answer question, the returned string array has only one element.

  • In the case of a multiple answer question, the returned string array has as many elements as answers selected by the user. Optional free text is ignored.

  • If the user has not fully answered the campaign (i.e. status is not fully), the returned string array is empty. Optional free text is ignored.

Note that, for security reasons, remote actions for self-help scenarios ignore the optional free text answers of multiple answer or opinion scale questions. Therefore, it is useless to include optional free text answers in campaigns to be used exclusively in self-help scenarios.

Example code

Find below a simple example of how to run a campaign from a remote action. The example assumes that you have created a single-answer campaign where one of the possible answers is yes:

Add-Type -Path "$env:NEXTHINK\RemoteActions\nxtcampaignaction.dll"

$CampaignUid  = "<UID of a single-answer campaign>"
$maxWaitTimeinSeconds = 60

$result = [Nxt.CampaignAction]::RunCampaign($CampaignUid, $maxWaitTimeinSeconds)
$status = [Nxt.CampaignAction]::GetResponseStatus($result)

if ($status -eq "fully") {
    $questionName = "question1"
    $choiceName =[Nxt.CampaignAction]::GetResponseAnswer($result, $questionName)
 if ($choiceName -eq "yes") {
        # user has confirmed - let's do some actions:
        Start-Process notepad.exe
    }
}

Error handling

Nexthink detects whether the execution of a remote action was successful or not based on the return value of the PowerShell process that ran the script:

  • An exit code value 0 indicates a successful execution.

  • A non-zero value indicates some kind of error.

However, unhandled exceptions in PowerShell may cause the termination of a script without returning an appropriate exit code. To handle unexpected errors, Nexthink recommends you to begin the body of all your scripts with the following code snippet:

 trap {
     $host.ui.WriteErrorLine($_.ToString())
     exit 1
 }

Place this default error handler right below the addition of the necessary DLL dependencies, which follow the optional declaration of formal parameters.

Performance measurement

nxtcfg.exe /s logmode=2

The operations described in this article should only be performed by a Nexthink Engineer or a Nexthink Certified Partner.

If you need help or assistance, please contact your Nexthink Certified Partner.


RELATED TASKS

RELATED REFERENCES

From the :

Ensure that you have , so they can run your signed scripts as well.

See a more elaborated .

To measure the performance and resource consumption of your scripts, turn on the logs of the Collector in debug mode with the help of the :

The output is stored in the .

Nexthink Act Scripting
Nexthink Act Security Whitepaper
Set-Authenticode
PowerShell certificate provider
example of self-help scenario with two campaigns here
Collector Configuration tool
Executing remote actions
Example of self-help scenario
Nexthink Act Scripting
Nexthink Act Security Whitepaper
deployed the appropriate signing certificates to the devices that run the Collector
nxtcod.log file