Need Help with Scripts and open templates

Hello all, I am currently trying to get ARM to run a script that move the user to a specific OU and to add it to specific group when using an open template to terminate a user. I created the Open template using the ARM Template generator. the PS script I am trying to run is this: 

param(
    [string] $UserName,
    [string] $targetDate,
    
)

try {
    # Asegurarse de que el script se ejecute incluso sin salida en la consola
    $ProgressPreference = "SilentlyContinue"
    
    $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
    
    $loginUrl = $baseUrl + "/Session/loginWithToken?token=$authZToken"
    
    $result = Invoke-RestMethod -uri $loginUrl -Method Get -SessionVariable websession
    Write-Host "Logon Result: $result"
    if (!$result.Success) {
        exit 5
    }
    $cookies = $websession.Cookies.GetCookies($loginUrl)
    
    $session.Cookies.Add($cookies)
    
    #------------------------------------------------
    # Configuración inicial
    $ADUser = $accountDn
    $EmailGroup = "Mail group NAME"
    $ExcludeGroup = "MAIL GROUP TO EXCLUDE"
    $TargetOU = "OU=TargetOU,OU=Site,DC=fqm,DC=COM"
    
    # Función para agregar un usuario a un grupo
    function Add-UserToGroup {
        param(
            [string]$UserName,
            [string]$GroupName
        )
        $User = Get-ADUser $UserName
        if ($User.Email -ne $null) {
            Add-ADGroupMember -Identity $GroupName -Members $User
        }
    }
    
    # Función para remover un usuario de todos los grupos excepto uno
    function Remove-UserFromGroups {
        param(
            [string]$UserName,
            [string]$ExcludeGroupName
        )
        $User = Get-ADUser $UserName
        $User | Get-ADPrincipalGroupMembership | Where-Object {$_.Name -ne $ExcludeGroupName} | ForEach-Object {
            Remove-ADGroupMember -Identity $_ -Members $User -Confirm:$false
        }
    }
    
    # Función para limpiar el campo de manager de un usuario
    function Clear-UserManager {
        param(
            [string]$UserName
        )
        Set-ADUser $UserName -Manager $null
    }
    
    # Función para mover un usuario a una OU específica
    function Move-UserToOU {
        param(
            [string]$UserName,
            [string]$TargetOU
        )
        Move-ADObject -Identity $UserName -TargetPath $TargetOU
    }
    
    # Lógica principal
    Add-UserToGroup -UserName $ADUser -GroupName $EmailGroup
    Remove-UserFromGroups -UserName $ADUser -ExcludeGroupName $ExcludeGroup
    Clear-UserManager -UserName $ADUser
    Move-UserToOU -UserName $ADUser -TargetOU $TargetOU
   

I am not an expert on PowerShell either on coding so will appreciate if you can provide me help about how to make it works on ARM. I have been looking for tutorials but there is not enough information about it.  Any help will be fully appreciated. 

this is the code of the Open template: 

[
  {
    "Version": 1,
    "TemplateType": "OpenTemplate",
    "Id": "68421248-a1d7-4a02-972e-533412254cd5",
    "DisplayName": "User Termination",
    "Description": "Terminate all user access and disabled the account. ",
    "IsManualInteractionRequired": "False",
    "ScriptToExecute": "User Terminationv2",
    "Form": {
      "Type": "Container",
      "Label": "User Termination",
      "Templates": [
        {
          "Key": "SAMAccountName",
          "Value": {
            "Type": "AccountSearchTextField",
            "Label": "User ID",
            "Description": "Network user ID used to logon on FQML network",
            "LookupTableId": "",
            "IsRequired": true,
            "AttributesToLoad": [
              ""
            ]
          }
        },
        {
          "Key": "targetDate",
          "Value": {
            "Type": "DatePicker",
            "Label": "Date to be deactivated",
            "Description": "Please specify when the account needs to be terminated. ",
            "ScriptParameterFormat": "M"
          }
        }
      ]
    }
  }
]

  • If you are looking to disable, not delete, an account and move it to a 'Recycle' OU, which can be defined in the AD Scan settings, here is the script I use. It doesn't have the add/remove group options but it might be a good start. 

    <#
    
    Scripts are not supported under any SolarWinds support program or service.
    Scripts are provided AS IS without warranty of any kind.
    SolarWinds further disclaims all warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose.
    The risk arising out of the use or performance of the scripts and documentation stays with you.
    In no event shall SolarWinds or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the scripts or documentation.
    
    #>
    param(
    [string] $authZToken,
    [string] $accountDn,
    [string] $targetDate,
    [string] $comment,
    [string] $baseUrl= "https://<ARM Server URL>"
    )
    try
    {
    # make sure that the script runs even without console output
    $ProgressPreference = "SilentlyContinue"
    
    $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
    
    $loginUrl = $baseUrl + "/Session/loginWithToken?token=$authZToken"
    
    $result = Invoke-RestMethod -uri $loginUrl -Method Get -SessionVariable websession
    Write-Host "Logon Result: $result"
    if (!$result.Success)
    {
    exit 5
    }
    $cookies = $websession.Cookies.GetCookies($loginUrl)
    
    $session.Cookies.Add($cookies);
    #------------------------------------------------
    $deactivateUserUrl = $baseUrl + "/api/v1/account/deactivateUser"
    $paramTemplate ='{ "userAccountDn": "user" , "moveToRecyclingOu": "True" , "Comment": "comment" , "ExecutionDate": "iso8601Date" }'
    $workerObj = $paramTemplate | ConvertFrom-Json
    $workerObj.userAccountDn = $accountDn
    $workerObj.Comment = $comment
    $workerObj.ExecutionDate = $targetDate
    
    $postBody = $workerObj | ConvertTo-Json
    
    Write-Host $postBody
    
    $result = Invoke-RestMethod -uri $deactivateUserUrl -WebSession $session -method Post -body $postBody -ContentType "application/json"
    Write-Host "Command Result: $result"
    
    #------------------------------------------------
    $logoutUrl = $baseUrl + "/Session/logout"
    
    $result1 = Invoke-RestMethod -uri $logoutUrl -WebSession $session -Method Get
    Write-Host "Logout Result: $result1"
    
    if ($result.Success)
    {
    Write-Host "Command without errors."
    exit 0
    }
    else
    {
    Write-Host "Command with an error."
    exit 1
    }
    }
    catch
    {
    Write-Host "Exit with an exception."
    Write-Host $Error
    }

    And here is the template. 

    [{
    "Version": 1,
    "TemplateType": "OpenTemplate",
    "Id": "<Unique UUID>",
    "DisplayName": "Deactivate User Account",
    "Description": "Order deactivation of a user account",
    "IsManualInteractionRequired": "false",
    "ScriptToExecute": "deactivateAccount",
    "Form": {
    "Type": "Container",
    "Label": "Request to deactivate a user",
    "Templates": [{
    "Key": "User",
    "Value": {
    "Type": "AccountSearchTextField",
    "Label": "Select User",
    "IsRequired": true,
    "LookupTableId": "AccountSearchResult",
    "AttributesToLoad": ["distinguishedname",
    "givenname",
    "objectguid"]
    }
    },
    {
    "Key": "TargetDate",
    "Value": {
    "Type": "DatePicker",
    "Label": "DeactivationDate",
    "IsRequired": true,
    "ScriptParameterFormat": "O"
    }
    },
    {
    "Key": "Account",
    "Value": {
    "Type": "TextField",
    "Label": "Hidden",
    "IsHidden": true,
    "Constraints": {
    "CreationRule": "<lookup>(AccountSearchResult,distinguishedname)"
    }
    }
    }]
    }
    }]

    The 'Recycle' OU can be set in the AD Scan Configuration as outlined here, https://documentation.solarwinds.com/en/success_center/arm/content/ad-change-configuration.htm