TextFilesHandling/Join-ITIObjectsTxtFile.ps1

<#
.SYNOPSIS
    Joins all .txt files from a specified directory to a single .txt file
.DESCRIPTION
    Joins all the files in the specified directory including the files from all subdirectories of the specified directory
.EXAMPLE
    Join-ITIObjectsTxtFile -SourcePath ~/MyProject/Apps -Destination ~/MyProject/allObjects.txt
.NOTES
    The function includes all .txt files. It does not include any other text files like .md.
#>

function Join-ITIObjectsTxtFile {
    [CmdletBinding()]
    param (
        # Directory where the .txt objects are stored
        [string] $SourcePath = './Apps',
        # Path to the file where the joint objects will be saved
        [string] $Destination = './objects.txt',
        # Specifies if progress bar should be shown
        [boolean] $ShowProgress = $true
    )
    if (SourcesInSubfolders($SourcePath)) {
        $objectFilesContent = JoinObjectsFromSubfolders $SourcePath $ShowProgress
    } else {
        $objectFilesContent = JoinObjectsFromFolder $SourcePath $ShowProgress
    }
    $objectFilesContent | Set-Content -Path $Destination -Encoding Oem
}

function SourcesInSubfolders($SourcePath) {
    $sourceFileList = Get-Item (Join-Path $SourcePath '*.txt')
    return ($null -eq $sourceFileList)
}


function MapObjectTypeToID($ObjectType){
    switch ($ObjectType) {
        'table' { return 1 }
        'report' { return 3 }
        'codeunit' { return 5 }
        'xmlport' { return 6 }
        'menusuite' { return 7 }
        'page' { return 8 }
        'query' { return 9} 
        Default { return 1 }
    }
}

function JoinObjectsFromSubfolders($SourcePath, $ShowProgress) {
    $objects = @()
    $subfolders = Get-ChildItem -Path $SourcePath -Directory | Sort-Object { MapObjectTypeToID $_.BaseName }
    foreach($subfolder in $subfolders){
        $subfolderPath = Join-Path $SourcePath $subfolder
        $objects += JoinObjectsFromFolder $subfolderPath $ShowProgress
    }
    return $objects
}

function ExtractIdFromFileName($Filename)
{
    $temp_name = $Filename -replace "[^0-9]",""
    if($temp_name -eq ""){
        $temp_name = "0"
    }
    return [Convert]::ToInt32($temp_name)
}

function JoinObjectsFromFolder($SourcePath, $ShowProgress) {
    if($ShowProgress) {
        Write-Progress -Activity 'Joining .txt files' -Status "Joining objects from $SourcePath" -PercentComplete 1
    }
    $objects = Get-Item -Path (Join-Path $SourcePath "*.txt") | Sort-Object { ExtractIdFromFileName $_.BaseName }  | Get-Content -Encoding Oem
    if($ShowProgress) {
        Write-Progress -Activity 'Joining .txt files' -Status "Joining objects from $SourcePath" -PercentComplete 100
    }
    return $objects
}

Export-ModuleMember -Function Join-ITIObjectsTxtFile