Delegated form PowerShell scripts (2024)

Table of Contents
Tip Note Tip Tip Tip Tip
  • HelloID
  • Service Automation
  • Delegated forms
  • Delegated form PowerShell scripts

Delegated form PowerShell scripts

You can configure delegated forms to run PowerShell scripts upon submission. This is where you use user-submitted form input to perform the necessary change in your organization's network.

Tip

Sometimes, you may need to run PowerShell code during a user's progression through a delegated form (as opposed to at the end, upon submission). In this case, split the underlying dynamic form into multiple steps, and use PowerShell data sources to execute code and populate form elements with the results.

To get started, Add a PowerShell script to a delegated form.

Add a PowerShell script to a delegated form

Note

Prerequisite: The Weather report delegated form shown in the Add a custom delegated form article.

  1. Go toDelegation>Delegated Forms and click Edit for the relevant form.

    For this example, we'll edit our Weather report delegated form.

  2. Go to the Task tab.

  3. We can choose to get any code snippet from our code snippet library or start with an default script. In our case we are starting with the default script.

  4. Click Set Default Script to populate the task with a default script template.

    Delegated form PowerShell scripts (1)

    Delegated form PowerShell scripts (2)

    Tip

    To start over at any time, delete all text from the script field. The Set Default Script button reappears.

    The key points about the script template are as follows. Examples are shown later in this article.

    • Wrap your code in a try/catch block.

    • Two types of logging are available: PowerShell console logging, and HelloID audit logging. See Logging in delegated form PowerShell scripts and Audit logging in delegated form PowerShell scripts. You can preview your PowerShell logs on the Received Logs tab, and your audit logs on the Received Audit Logs tab.

    • You have access to $form and $requester, which are available in autocomplete. Open autocomplete by typing $. You also have access to all System variables, Custom variables, which are not included in autocomplete.

      Delegated form PowerShell scripts (3)

      Changes you make on the Form tab are immediately available in the $form variable's autocomplete on the Task tab.

    • Use the Run In Cloud toggle to choose whether this script will run using the Cloud Service Automation Agent (enabled) or the On-premises Service Automation Agent (disabled).

    • The Input tab lets you specify JSON form input in order to simulate form input to the $form variable, to test your script.

      Tip

      To generate test JSON based on a form, Generate test JSON.

    • Email sends in delegated form PowerShell scripts are supported, but it's not currently possible to preview them when testing your script.

    • Delegated form PowerShell scripts do not return any data to HelloID.

  5. Customize the script according to what should happen when a user submits this delegated form. For example, make API calls into external systems based on the data available in the form or requester objects.

    For this example, we will query a weather API (similar to the script demonstrated in the Add a PowerShell data source article), and show some important variables in action. We'll use the following script:

    ######################################################################## Template: HelloID SA Delegated form task# Name: Weather report DGF# Date: 8.9.2023########################################################################region init$VerbosePreference = "SilentlyContinue"$InformationPreference = "Continue"$WarningPreference = "Continue"# global variables (Automation --> Variable libary):$globalVarExample = $companyName# variables configured in form:$formVarExample = $($form.tempUnitDropdown.tempUnitValue)# other variables$requesterUsernameExample = $requester.userName$requesterUserGUIDExample = $requester.userGUID#endregion init#region functionsFunction Get-Current-NYC-Weather { $locationEndpoint = "https://api.open-meteo.com/v1/forecast?latitude=40.71&longitude=-74.01&hourly=temperature_2m&temperature_unit=$formVarExample&windspeed_unit=mph&precipitation_unit=inch" $response = Invoke-RestMethod -uri $locationEndpoint Write-Information "Response: $response" return @{weather = "Current time: $($response.hourly.time[0]); current temperature: $($response.hourly.temperature_2m[0]) degrees $formVarExample"}}#endregion functions#region tasktry { Write-Verbose "Looking up NYC weather for [$requesterUsernameExample ($requesterUserGUIDExample)], in product $productName" $result = Get-Current-NYC-Weather Write-Information "Result: $($result.weather)" $Log = @{ Action = "Undefined" System = "OpenMeteo" Message = "Successfully executed action for [$requesterUsernameExample ($requesterUserGUIDExample)]" IsError = $false TargetDisplayName = $requesterUsernameExample TargetIdentifier = $([string]$requesterUserGUIDExample) } Write-Information -Tags "Audit" -MessageData $log $email = @{ from = "[emailprotected]" to = "[emailprotected]" subject = "Your weather report" body = "<strong>$($result.weather)</strong>" confidential= $false } Write-Information -Tags "Email" $email} catch { $ex = $PSItem Write-Warning "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($ex.Exception.Message)" Write-Error "Error executing action for [$requesterUsernameExample ($requesterUserGUIDExample)]. Error Message: $($ex.Exception.Message)" $Log = @{ Action = "Undefined" System = "OpenMeteo" Message = "Error executing action for [$requesterUsernameExample ($requesterUserGUIDExample)]. Error Message: $($ex.Exception.Message)" IsError = $true TargetDisplayName = $requesterUsernameExample TargetIdentifier = $([string]$requesterUserGUIDExample) } Write-Information -Tags "Audit" -MessageData $log}#endregion task

    Delegated form PowerShell scripts (4)

  6. If your script relies on form data, enter JSON in the Input tab to simulate form input.

    For this example, we'll enter the following JSON to simulate input from our Weather report form:

    { "tempUnitDropdown": { "tempUnitLabel": "Fahrenheit", "tempUnitValue": "fahrenheit" }}

    Delegated form PowerShell scripts (5)

  7. To test your script, click Execute PowerShell. View the results on the Received Logs and Received Audit Logs tabs.

    For this example, the NYC weather has been fetched and logged.

    Delegated form PowerShell scripts (6)

    Delegated form PowerShell scripts (7)

  8. ClickSave.

To view the results in production, View submissions.

Logging in delegated form PowerShell scripts

Delegated form PowerShell scripts use native PowerShell logging.

  • Write-Information "Information"

  • Write-Host "Equivalent to Write-Information"

  • Write-Error "An error"

  • Write-Warning "A warning"

  • Write-Verbose -Verbose "Verbose requires the -Verbose flag"

  • Write-Debug -Debug "Debug requires the -Debug flag"

Tip

HelloID interprets Write-Error messages as task failure, in which case the task execution will be labeled Failed in Activities. When a user submits a delegated form on the Servicedesk and it fails, they will receive a Submission failure notification.

When testing your script, you can preview log messages on the Received Logstab. To view them in production, View PowerShell logs.

Control which PowerShell log levels are shown on the Received Logs tab using the $VerbosePreference, $InformationPreference, and $WarningPreference variables. Levels set to Continue will be shown. Levels set to SilentlyContinue will not.

Audit logging in delegated form PowerShell scripts

HelloID's Audit logs store information long-term for organizational audits or compliance. Audit logs are separate from PowerShell script logging.

In Delegated form PowerShell scripts, write custom messages into the audit logs using the following template:

$Log = @{Action = "CreateAccount"System = "ActiveDirectory"Message = "Created account with username [emailprotected]"IsError = $falseTargetDisplayName = "Jan Willem (1000)"TargetIdentifier = "AD-SID"}Write-Information -Tags "Audit" -MessageData $Log

To preview audit logs while testing your script, go to the Received Audit Logs tab. To view audit logs in production, View audit logs or view them in the main Audit logs interface.

Action

An enum that describes what the delegated form does. If no value is specified, it is set toUndefined. Optional.

  • Undefined

  • CreateAccount

  • EnableAccount

  • UpdateAccount

  • DisableAccount

  • MoveAccount

  • DeleteAccount

  • GrantMembership

  • RevokeMembership

  • CreateResource

  • UpdateResource

  • DeleteResource

  • SendNotification

  • SetPassword

System

A string that contains the name of the system that the delegated form modified. Optional.

Message

A string that describes the action taken. Required.

IsError

A boolean that reports whether the form succeeded ($false; default) or failed ($true). Optional.

TargetDisplayName

A string that contains the display name of the object that the form modified. Optional.

TargetIdentifier

A string that contains the unique identifier of the object that the form modified. Optional.

Email sends in delegated form PowerShell scripts

Delegated form PowerShell scripts support email sends via the following template:

$email = @{ from = "[emailprotected]" to = "[emailprotected]" cc = "[emailprotected]" bcc = "[emailprotected]" subject = "Created account with username [emailprotected]" body = "<strong>This is the email body.</strong>" confidential= $false } Write-Information -Tags "Email" $email

Whenconfidentialis set to$false, the email and its contents are automatically logged inthe Audit logs. When it is set to$true, the email isnotlogged.

When the Write-Information cmdlet is used with theEmailtag, it only sends the specified hash table as an email. It does not create a PowerShell log entry.

The from address must either 1) have a verified domain (see Configure a custom 'from' address for emails), or 2) be set to [emailprotected]. Otherwise, the send will fail.

Tip

Emails are only sent when the script runs in production. No emails are sent when the script is tested in preview.

In this section:

Delegated form PowerShell scripts (2024)
Top Articles
Latest Posts
Article information

Author: Rueben Jacobs

Last Updated:

Views: 6124

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Rueben Jacobs

Birthday: 1999-03-14

Address: 951 Caterina Walk, Schambergerside, CA 67667-0896

Phone: +6881806848632

Job: Internal Education Planner

Hobby: Candle making, Cabaret, Poi, Gambling, Rock climbing, Wood carving, Computer programming

Introduction: My name is Rueben Jacobs, I am a cooperative, beautiful, kind, comfortable, glamorous, open, magnificent person who loves writing and wants to share my knowledge and understanding with you.