Public/Set-ALRulesetRule.ps1

<#
.SYNOPSIS
Adds rules (as defined by -ID, -Action and -Justification) to the given paths.
.DESCRIPTION
Use -Force to overwrite existing rules with the same ID.
Use -SkipSort to skip sorting the rules by ID afterwards.
#>

function Set-ALRulesetRule
{
    param
    (
        [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias("FullName")]
        [string[]]$Path,

        [Parameter(Mandatory, Position = 1)]
        [string[]]$ID,

        [Parameter(Mandatory, Position = 2)]
        [Action]$Action,

        [Parameter()]
        [string]$Justification,

        [switch]$Force,

        [switch]$SkipSort
    )

    process
    {
        $Path
        | ForEach-Object {
            $Ruleset = Get-Content -Path $_ -Raw | ConvertFrom-Json -Depth 5
            $AnyChange = $false

            $ID | ForEach-Object {
                if ($Force -or (-not ($Ruleset.Rules | Where-Object ID -EQ $_)))
                {
                    $AnyChange = $true

                    $Rule = [ordered]@{}
                    $Rule.id = $_
                    $Rule.action = $Action.ToString()
                    if ($Justification) { $Rule.justification = $Justification }

                    $Ruleset.Rules = @(
                        ($Ruleset.Rules | Where-Object ID -NE $_)
                        $Rule
                    )
                }
            }

            if ($AnyChange)
            {
                if (-not $SkipSort)
                {
                    $Ruleset.Rules = $Ruleset.Rules | Sort-Object -Property $ID
                }

                $Ruleset
                | ConvertTo-Json -Depth 5
                | Set-Content -Path $_ -NoNewline
            }
        }
    }
}