Skip to main content

HelloID

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.

  1. Go to Delegation > 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.

    2023-08-08_14-41-08.jpg
    2023-08-08_14-41-50.jpg

    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.

  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 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
    2023-08-09_10-20-57.jpg
  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"
       }
    }
    2023-08-09_10-21-10.jpg
  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.

    2023-08-09_10-05-44.jpg
    2023-08-09_10-06-01.jpg
  8. 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.