AL/Test-TablePermissionsExist.ps1

<#
 .Synopsis
  Tests if permissions for all tables exist
 .Description
  Tests if the project has a permissions file and if all tables are defined in the permissions file
 .Parameter SourcePath
  Path to the current project
 .Parameter KeyName
  Name of the key the value should be updated
 .Parameter KeyValue
  New Value for the key
 .Example
  Set-AppKeyValue -KeyName "publisher" -KeyValue "test"
#>

function Test-TablePermissionsExist {
    param (
        # Source path of app code
        [Parameter(Mandatory=$false)]
        [string]
        $SourcePath = (Get-Location),
        # Do not throw an error if a table permission is found to be missing
        [Parameter(Mandatory=$false)]
        [switch]
        $SuppressError
    )

    $Tables = Get-ChildItem $SourcePath -Recurse -Filter '*.al' | Where-Object {(Get-Content $_.FullName).Item(0).StartsWith('table ')} | Where-Object {(Split-Path (Split-Path $_.FullName -Parent) -Leaf) -ne 'Tests'}

    if ($null -eq $Tables) {
        return $true
    }

    $PermissionFile = (Get-ChildItem $SourcePath -Recurse -Filter '*.xml' | Where-Object {(Get-Content $_.FullName -Raw).Contains('PermissionSets')}).FullName

    if ($null -eq $PermissionFile) {
        throw "Permissions file not found"
    }

    [xml]$PermissionsContent = Get-Content $PermissionFile
    foreach ($Table in $Tables) {
        $TableID = (Get-Content $Table.FullName).Item(0)
        $TableID = $TableID.Substring(6,$TableID.IndexOf(' ',7) - 6)
        if (($PermissionsContent.SelectNodes("PermissionSets/PermissionSet/Permission[ObjectType='0' and ObjectID='{0}']" -f $TableID)).Count -eq 0) {
            if ($SuppressError.IsPresent) {
                return $false
            }
            else {
                throw "Permission for table $TableID could not be found in permission file {0}" -f $PermissionFile
            }
        }
    }

    return $true
}

Export-ModuleMember -Function Test-TablePermissionsExist