How to use templatefile to pass a powershell script into CommandToExecute

Hi folks,

I am trying to load a PowerShell script as part of the deployment to avoid using external dependencies when deploying a custom script extension for a windows virtual machine but I’m facing this issue.

Error: "settings" contains an invalid JSON: invalid character '\n' in string literal

on compute.tf line 94, in resource "azurerm_virtual_machine_extension" "example":
94: resource "azurerm_virtual_machine_extension" "example" {

Here’s a part of my PowerShell script.
<#
.SYNOPSIS
Synopsis

.DESCRIPTION
Description

.PARAMETER FirstParameter
FirstParameter

.PARAMETER SecondParameter
SecondParameter

.EXAMPLE
.\script.ps1 -FirstParameter <value> -SecondParameter <value>
#>

Param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$FirstParameter

[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SecondParameter

try 
{
# Do stuff
Write-Output "Enabling TLS 1.2."
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12

Write-Output "Doing stuff..."
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Write-Output "Doing stuff..."
choco install package --params "/PARAM:$FirstParameter" -y

Write-Output "Doing stuff..."
Add-LocalGroupMember -Group "Group" -Member $SecondParameter
}
catch
{
Write-Error $_.Exception
throw $_.Exception
}
finally
{
Write-Host "Did stuff..."
$LASTEXITCODE
}

Here’s the Terraform part.
resource “azurerm_virtual_machine_extension” “example” {
for_each = azurerm_windows_virtual_machine.machines
name = “extension”
virtual_machine_id = azurerm_windows_virtual_machine.machines[each.key].id
publisher = “Microsoft.Compute”
type = “CustomScriptExtension”
type_handler_version = “1.10”

  settings = <<SETTINGS
{
  "commandToExecute": "powershell.exe -executionpolicy bypass -command ${templatefile("script.ps1", { FirstParameter = "Some value", SecondParameter = "${var.localadmin}" } ) }"
}
  SETTINGS
}

I’ve tried to use jsonencode(), convert my script line endings to unix style and many other things but didn’t found out how to solve this issue.

Appreciate your help on this.