TextFilesHandling/Split-ITIObjectsTxtFile.ps1

<#
.SYNOPSIS
    Splits a .txt file that contains NAV objects and saves each object as an individual file
.DESCRIPTION
    This command reads the .txt file that contains multiple objects, splits the objects and saves each object in a proper subdirectory according to it's type
.EXAMPLE
    Split-ITIObjectsTxtFile -SourcePath ~/MyProject/allObjects.txt -Destination ~/MyProject
.NOTES
    The functions splits the source file into seven subfolders: codeunit, page, query, report, table, xmlport, menusuite
#>

function Split-ITIObjectsTxtFile {
    [CmdletBinding()]
    param (
        # The path to the .txt file containing multiple NAV objects
        [string] $SourcePath = './objects.txt',
        # The path where the seperate files will be saved
        [string] $Destination = './Apps',
        # Specifies if progress bar should be shown
        [boolean] $ShowProgress = $true
    )
    if($ShowProgress) {
        Write-Progress -Activity 'Splitting .txt file' -Status 'Enumerating objects' -PercentComplete 0
    }
    $object = [System.Collections.ArrayList]@();
    $objnumber = 0;
    (Get-Content -Encoding Oem $SourcePath -Raw) -split [Environment]::NewLine | foreach-object {
        if ($_ -cmatch "OBJECT\s") {
            $objnumber = $object.Add($_+[Environment]::NewLine);
        } else {
            if ($_ -cmatch ("\s\s\s\sDate=") -or $_ -cmatch ("\s\s\s\sTime=")) {
                $object[$objnumber] += $_.Substring(0,$_.IndexOf('=') + 1) + ';' + [Environment]::NewLine;
            } elseif ($_ -cnotmatch ("\s\s\s\sModified=")) {
                $object[$objnumber] += $_ + [Environment]::NewLine;   
            }
        }
    };
    if($ShowProgress) {
        Write-Progress -Activity 'Splitting .txt file' -Status 'Enumerating objects' -PercentComplete 100
    }
    for ($i = 0; $i -lt $object.Count; $i++) {
        if($ShowProgress) {
            Write-Progress -Activity 'Splitting .txt file' -Status 'Splitting objects' -PercentComplete ($i/$object.Count*100)
        }
        $firstLine = ($object[$i] -split [Environment]::NewLine)[0];
        $separatedWords = $firstLine.split(" ");
        $prefix = $separatedWords[1].Substring(0,3).ToUpper()
        $FileName =  $prefix + $separatedWords[2];
        $FileDestination = Join-Path $Destination $SourceSubfoldersMap[$prefix]
        if (-Not(Test-Path $FileDestination)) {
            New-Item $FileDestination -ItemType Directory
        }
        $object[$i].trim() | Out-File (Join-Path $FileDestination ($FileName + ".txt")) -Encoding oem
    }
}
Export-ModuleMember -Function Split-ITIObjectsTxtFile