AL/Test-TablePermissionsExist.ps1

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 '*.al' | Where-Object {(Get-Content $_.FullName).Item(0).StartsWith('permissionset ')} | Where-Object {(Split-Path (Split-Path $_.FullName -Parent) -Leaf) -ne 'Tests'}).FullName
    if ($null -ne $PermissionFile)
    {
        $PermissionsContent = Get-Content $PermissionFile
        foreach ($Table in $Tables) {
            $TableName = (Get-Content $Table.FullName).Item(0)
            $TableName = $TableName.Substring($TableName.IndexOf('"'))
            $TablePermissionExists = ($PermissionsContent -match ("table[ ]+" + $TableName)).Count -ne 0
            $TableDataPermissionExists = ($PermissionsContent -match ("tabledata[ ]+" + $TableName)).Count -ne 0
            if (!($TablePermissionExists -and $TableDataPermissionExists)) {
                if ($SuppressError.IsPresent) {
                    return $false
                }
                else {
                    throw "Permission for table $TableName could not be found in permission file {0}" -f $PermissionFile
                }
            }
        }
    } 
    else {
        $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