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.
Note
Prerequisite: The Weather report
delegated form shown in the Add a custom delegated form article.
Go to Delegation > Delegated Forms and click Edit for the relevant form.
For this example, we'll edit our
Weather report
delegated form.Go to the Task tab.
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.
Click Set Default Script to populate the task with a default script template.
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.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.
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 functions Function 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 task try { 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 = "[email protected]" to = "[email protected]" 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
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" } }
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.
Click Save.
To view the results in production, View submissions.
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 Logs tab. 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.
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 [email protected]" IsError = $false TargetDisplayName = "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 to
Undefined
. 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.
Delegated form PowerShell scripts support email sends via the following template:
$email = @{ from = "[email protected]" to = "[email protected]" cc = "[email protected]" bcc = "[email protected]" subject = "Created account with username [email protected]" body = "<strong>This is the email body.</strong>" confidential= $false } Write-Information -Tags "Email" $email
When confidential
is set to $false
, the email and its contents are automatically logged in the Audit logs. When it is set to $true
, the email is not logged.
When the Write-Information cmdlet is used with the Email
tag, 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 [email protected]
. 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.