(view source code of airreglycmd.ps as plain text)
<#
.SYNOPSIS
Search a downloaded Lithuanian aircraft register database for an aircraft registation and if found, return the aircraft model
.DESCRIPTION
First, create a subdirectory 'LY' in this script's parent folder.
Next, download the Lithuanian aircraft register database (see links section), unzip it and move the PDF file to the 'LY' folder.
Now run this script with an aircraft registration as its only parameter (see examples section).
The script cannot read the PDF file directly, so the PDF file needs to be converted to plain text first.
The script will look for a GhostScript installation on the computer, and if found, uses the following command to convert the PDF file to plain text:
"C:\Program Files\gs\gs<version>\bin\gswin64c.exe" -sDEVICE=txtwrite -o Lietuvos-Respublikoje-registruotu-orlaiviu-sarašas.txt Lietuvos-Respublikoje-registruotu-orlaiviu-sarašas.pdf
NOTE: If you download a new PDF file, make sure to either run this script with the -ConvertPDF switch or manually delete the old TEXT file!
The script will search for a line that starts with the registration.
If a match is found, the model will be in the same line, more to the right.
The script will display a tab-delimited string with the registration and the aircraft model (<registration><tab><tab><model>).
If the script was started by another PowerShell script, the calling PowerShell script may also read the model from the variable $Model, passed on by this script.
If the script was started by a batch file, the calling batch file can use 'FOR /F' on this PowerShell script's screen output to find the model.
Get-Help './AirRegLYCmd.ps1' -Examples will show 2 examples of this script being called by another script.
.PARAMETER Registration
A valid Lithuanian aircraft registration, i.e. LY-xxx (where each x is a single character)
.PARAMETER ConvertPDF
Force conversion of the latest PDF file to plain text; use this switch once after downloading a new PDF file.
.PARAMETER Quiet
Ignore all errors and do not display any error messages; in case of errors, just terminate with return code 1.
.PARAMETER Help
Show the script's help screen
.PARAMETER Version
Show this script's version number; if combined with -Verbose show full script path, version number and last/modified/release date
.PARAMETER Debug
Show some progress messages
.OUTPUTS
A tab-delimited string <registration><tab><tab><model> and model is also stored in output variable $Model.
.EXAMPLE
. ./AirRegLYCmd.ps1 "LY-LAM"
Will return tab-delimited string "LY-LAM<tab><tab>TIGER MOTH Replika", and set variable $Model to "TIGER MOTH Replika"
.EXAMPLE
"LY-LAM" | . ./AirRegLYCmd.ps1
Will also return tab-delimited string "LY-LAM<tab><tab>TIGER MOTH Replika", and set variable $Model to "TIGER MOTH Replika"
.EXAMPLE
. ./AirRegLYCmd.ps1 "LY-LAM" -Debug
This will return:
Started search for local database (text format) in folder ".\LY" at <date> <time>
Start searching LY LAM in .\LY\Lietuvos-Respublikoje-registruotu-orlaiviu-sarašas.txt file at <date> <time>
Found a match at <date> <time>
LY-LAM TIGER MOTH Replika
Finished at <date> <time> (elapsed time <time elapsed>)
.EXAMPLE
. ./AirRegLYCmd.ps1 -Version -Verbose
Will return the full script path, version and last modified/release date
.EXAMPLE
. ./AirRegLYCmd.ps1 -Version
Will return the script version
.EXAMPLE
Create and run the following PowerShell script:
===============================================================
$Registration = 'OE-AKJ' ; $Manufacturer = '' ; $Model = ''
[void] ( . "$PSScriptRoot\AirRegOECmd.ps1" -Registration $Registration )
Write-Host ( "Registration : {0}`nManufacturer : {1}`nModel : {2}" -f $Registration, $Manufacturer, $Model )
===============================================================
Besides setting variables $Manufacturer to "BOEING" and $Model to "E75", it will return:
Registration : LY-LAM
Manufacturer :
Model : TIGER MOTH Replika
.EXAMPLE
Create and run the following batch file:
===============================================================
REM Note that there should only be a TAB and nothing else between delims= and the doublequote
FOR /F "tokens=1-3 delims= " %%A IN ('powershell . ./AirRegOECmd.ps1 OE-AKJ') DO (
ECHO Registration : %%A
ECHO Manufacturer :
ECHO Model : %%B
)
===============================================================
It will return:
Registration : LY-LAM
Manufacturer :
Model : TIGER MOTH Replika
.LINK
Script written by Rob van der Woude:
https://www.robvanderwoude.com/
.LINK
Lithuanian aircraft register database:
https://tka.lt/oro-transportas/katalogas/register-of-civil-aircraft-of-the-republic-of-lithuania/?lang=en
.LINK
GhostScript download page:
https://www.ghostscript.com/download/gsdnld.html
.LINK
Convert PDF to text by user2176753 on StackOverflow.com:
https://stackoverflow.com/a/26405241
.LINK
Capture -Debug parameter by mklement0 on StackOverflow.com:
https://stackoverflow.com/a/48643616
#>
param (
[parameter( ValueFromPipeline )]
[ValidatePattern("(^\s*$|[\?/]|^LY-[A-Z]{3}$)")]
[string]$Registration,
[switch]$ConvertPDF,
[switch]$Quiet,
[switch]$Help,
[switch]$Version
)
$progver = "1.00"
$Registration = $Registration.ToUpper( )
[string]$Manufacturer = ''
[string]$Model = ''
[bool]$Debug = ( $PSBoundParameters.ContainsKey( 'Debug' ) )
[bool]$Verbose = ( $PSBoundParameters.ContainsKey( 'Verbose' ) )
if ( $Version ) {
if ( $Verbose ) {
$lastmod = ( [System.IO.File]::GetLastWriteTime( $PSCommandPath ) )
if ( $lastmod.ToString( "h.mm" ) -eq $progver ) {
"`"{0}`", Version {1}, release date {2}" -f $PSCommandPath, $progver, $lastmod.ToString( "yyyy-MM-dd" )
} else {
# if last modified time is not equal to program version, the script has been tampered with
"`"{0}`", Version {1}, last modified date {2}" -f $PSCommandPath, $progver, $lastmod.ToString( "yyyy-MM-dd" )
}
} else {
$progver
}
exit 0
}
function ShowHelp( $errormessage = '' ) {
if ( !$Quiet ) {
Clear-Host
if ( $errormessage ) {
Write-Host
Write-Host "Error: " -ForegroundColor Red -NoNewline
Write-Host $errormessage
}
Write-Host
Write-Host ( "`"{0}`", Version {1}" -f $PSCommandPath, $progver ) -NoNewline
$lastmod = ( [System.IO.File]::GetLastWriteTime( $PSCommandPath ) )
if ( $lastmod.ToString( "h.mm" ) -eq $progver ) {
Write-Host ", release date " -NoNewline
} else {
# if last modified time is not equal to program version, the script has been tampered with
Write-Host ", last modified date " -NoNewline
}
Write-Host $lastmod.ToString( "yyyy-MM-dd" )
Write-Host
Get-Help $PSCommandPath -Full
}
}
if ( $Help -or $Registration -match '(^\s*$|[\?/])' ) {
ShowHelp
exit 1
}
function GetGhostscript( ) {
# Check if GhostScript is installed, and if so, return the path to the command line execuatable
$gskey = $null
$gspath = ''
$gsprog = ''
if ( $Debug ) {
Write-Host ( "Start searching the registry for GhostScript installations at {0}" -f ( Get-Date ) )
}
$gskey = ( ( Get-ChildItem -Path registry::'HKEY_LOCAL_MACHINE\SOFTWARE' -Recurse -Depth 2 -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'ghostscript' } | Select-Object -First 1 ) | Get-ChildItem | Sort-Object { [double]$_.PSChildName } | Select-Object -Last 1 ).Name
if ( $gskey ) {
if ( $Debug ) {
Write-Host ( "Found GhostScript installation in the registry: `"{0}`" at {1}" -f $gskey, ( Get-Date ) )
}
$gspath = ( Get-ItemProperty -Path "Registry::$gskey" ).'(default)'
if ( $gspath ) {
if ( $Debug ) {
Write-Host ( "Found GhostScript path in the registry: `"{0}`"" -f $gspath )
}
$gsprog = ( Get-ChildItem -Path "$gspath" -Filter 'gs*c.exe' -Recurse ).FullName
if ( $Debug ) {
Write-Host ( "Found GhostScript executable: `"{0}`"" -f $gsprog )
}
}
}
$gsprog
}
function Convert-PDF2Text( [string]$pdffile, [string]$textfile = '' ) {
if ( $Debug ) {
Write-Host ( "Trying to convert downloaded PDF aircraft registry database file `"{0}`" to plain text at {1}" -f $pdffile, ( Get-Date ) )
Write-Host "First, try and find GhostScript"
}
$gsexec = ( GetGhostScript )
if ( [string]::IsNullOrWhiteSpace( $gsexec ) ) {
if ( !$Quiet ) {
Write-Host "GhostScript not found on this computer"
}
$false
} else {
if ( $Debug ) {
Write-Host ( "GhostScript command line executable found: `"{0}`"" -f $gsexec )
}
if ( Test-Path -Path "$pdffile" -PathType 'Leaf' ) {
if ( $Debug ) {
Write-Host "PDF file found"
}
if ( [string]::IsNullOrWhiteSpace( $textfile ) ) {
$parentfolder = [System.IO.Directory]::GetParent( $pdffile )
$textfilename = [System.IO.Path]::GetFileNameWithoutExtension( $pdffile )
$newtextfile = ( Join-Path -Path "$parentfolder" -ChildPath "$textfilename.txt" )
$oldtextfile = ( Join-Path -Path "$parentfolder" -ChildPath "$textfilename.old" )
if ( $Debug ) {
Write-Host ( "New text file will be `"{0}`'" -f $newtextfile )
}
if ( Test-Path -Path "$newtextfile" -PathType 'Leaf' ) {
if ( $debug ) {
Write-Host "Text file already exist"
}
if ( Test-Path -Path $oldtextfile -PathType 'Leaf' ) {
if ( $Debug ) {
Write-Host ( "Deleting old text file `"{0}`"" -f $oldtextfile )
}
[System.IO.File]::Delete( $oldtextfile )
}
if ( $Debug ) {
Write-Host ( "Renaming existing text file `"{0}`" to `"{1}`"" -f $newtextfile, $oldtextfile )
}
[System.IO.File]::Move( $newtextfile, $oldtextfile )
}
} else {
$newtextfile = $textfile
if ( $Debug ) {
Write-Host ( "New text file will be `"{0}`'" -f $newtextfile )
}
}
if ( $Debug ) {
Write-Host ( "Actual conversion started at {0} using the command:" -f ( Get-Date ) )
Write-Host "`"$gsexec`" -sDEVICE=txtwrite -o `"$newtextfile`" `"$pdffile`""
}
( . "$gsexec" -sDEVICE=txtwrite -o "$newtextfile" "$pdffile" )
$true
} else {
if ( $Debug -or !$Quiet ) {
Write-Host ( "Downloaded PDF aircraft registry database file `"{0}`" not found" -f $pdffile )
}
$false
}
}
}
$LY_mark = $Registration.Substring( 3 )
$dbfile = ''
$dbfolder = ( Join-Path -Path $PSScriptRoot -ChildPath 'LY' )
if ( $Debug ) {
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew( )
}
if ( $ConvertPDF ) {
$ErrorActionPreference = 'SilentlyContinue'
$pdffile = ( Get-ChildItem -Path $dbfolder -Filter 'Lietuvos-*.pdf' | Sort-Object -Property 'Name' | Select-Object -Last 1 ).FullName
$ErrorActionPreference = 'Continue'
if ( $Debug ) {
Write-Host "-ConvertPDF switch used, convert latest PDF to plain text first"
Write-Host ( "Started search for local database (PDF format) in folder `"{0}`" at {1}" -f $dbfolder, ( Get-Date ) )
}
if ( Convert-PDF2Text $pdffile ) {
$pdffilename = [System.IO.Path]::GetFileNameWithoutExtension( $pdffile )
$dbfile = ( Join-Path -Path $dbfolder -ChildPath "$pdffilename.txt" )
}
} else {
if ( $Debug ) {
Write-Host ( "Started search for local database (text format) in folder `"{0}`" at {1}" -f $dbfolder, ( Get-Date ) )
}
$ErrorActionPreference = 'SilentlyContinue'
$dbfile = ( Get-ChildItem -Path $dbfolder -Filter 'Lietuvos-*.txt' | Sort-Object -Property 'Name' | Select-Object -Last 1 ).FullName
$ErrorActionPreference = 'Continue'
}
if ( [string]::IsNullOrWhiteSpace( $dbfile ) ) {
if ( $Quiet -and !$Debug ) {
exit 1
} else {
if ( $Debug ) {
Write-Host "Converted text file not found, looking for original PDF aircraf registry database file"
}
$textfilename = [System.IO.Path]::GetFileNameWithoutExtension( $dbfile )
$pdffile = ( Join-Path -Path $dbfolder -ChildPath "$textfilename.pdf" )
if ( Test-Path $pdffile -PathType 'Leaf' ) {
if ( $Debug ) {
Write-Host ( "Founf PDF file `"{0}`"" -f $pdffile )
}
$message = "A PDF database file was found, but it needs to be converted to text for this script to function.`n`nDo you want to convert the PDF file to a plain text file now?"
$title = "PDF to Text Conversion Required"
$buttons = [System.Windows.Forms.MessageBoxButtons]::YesNo
$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
if ( $answer = 'Yes' ) {
if ( Convert-PDF2Text $pdffile ) {
if ( $Debug ) {
Write-Host "PDF to text conversion completed"
}
} else {
if ( $Debug -or !$Quiet ) {
Write-Host "PDF to text conversion failed"
exit 1
}
}
} else {
if ( $Debug -or !$Quiet ) {
Write-Host "Please convert your PDF aircraft registry database file to plain text and try again"
}
exit 1
}
}
}
}
if ( $dbfile ) {
if ( $Debug ) {
Write-Host ( "Start searching LY {0} in {1} file at {2}" -f $LY_mark, $dbfile, ( Get-Date ) )
}
$found = $false
( Get-Content -Path $dbfile ).Split( "`n" ) | ForEach-Object {
if ( !$found ) {
$pattern = "^\s{{11,17}}LY\s{{8,}}{0}\s" -f $LY_mark
if ( $_ -match $pattern ) {
if ( $Debug ) {
Write-Host ( "Found a match at {0}" -f ( Get-Date ) )
}
$pattern = "[12][09]\d\d\.[01]\d\.[0-3]\d\s+(.*)"
$Model = [System.Text.RegularExpressions.Regex]::Match( $_, $pattern ).Captures.Groups[1]
if ( $Model -match "[12][09]\d\d\.[01]\d\.[0-3]\d\s*$" ) {
$pattern = "(.*)[12][09]\d\d\.[01]\d\.[0-3]\d\s*$"
$Model = [System.Text.RegularExpressions.Regex]::Match( $Model, $pattern ).Captures.Groups[1]
}
$Model = $Model.Trim( )
# Remove the following words at the start of the line:
# Dirižablis, Hidroplanas, Lektuvas, Malunsparnis, MKO, MKO/UL,
# Motosklandytuvas, Motoskraidykle, Oro balionas, Sklandytuvas,
# Sraigtasparnis, Ultralengvasis
$pattern = "^(Diri.{1,2}ablis|Hidroplanas|L.{1,2}ktuvas|Mal.{1,2}nsparnis|MKO|MKO/UL|Motosklandytuvas|Motoskraidykl.{1,2}|Oro balionas|Sklandytuvas|Sraigtasparnis|Ultralengvasis)"
$Model = [System.Text.RegularExpressions.Regex]::Replace( $Model, $pattern, "" )
$Model = $Model.Trim( )
# Remove text between parentheses from begin of model
$pattern = "^\s*\([^\)]+\)\s*"
if ( $Model -match $pattern ) {
$Model = [System.Text.RegularExpressions.Regex]::Replace( $Model, $pattern, "" )
}
# Remove "/ Sailplane" of which the "plane" part will be garbled through the model text due to columns in PDF being too narrow
if ( $Model.StartsWith( "/ Sail" ) ) {
$newmodel = $Model.Substring( 6 )
# Remove first lower case "p"
$p = $newmodel.IndexOf( 'p', [System.StringComparison]::InvariantCulture )
if ( $p -ne -1 ) {
$newmodel = ( "{0}{1}" -f $newmodel.Substring( 0, $p ), $newmodel.Substring( $p + 1 ) )
# Remove first lower case "l" following removed "p"
$l = $newmodel.IndexOf( 'l', $p, [System.StringComparison]::InvariantCulture )
if ( $l -ne -1 ) {
$newmodel = ( "{0}{1}" -f $newmodel.Substring( 0, $l ), $newmodel.Substring( $l + 1 ) )
# Remove first lower case "a" following removed "l"
$a = $newmodel.IndexOf( 'a', $l, [System.StringComparison]::InvariantCulture )
if ( $a -ne -1 ) {
$newmodel = ( "{0}{1}" -f $newmodel.Substring( 0, $a ), $newmodel.Substring( $a + 1 ) )
# Remove first lower case "n" following removed "a"
$n = $newmodel.IndexOf( 'n', $a, [System.StringComparison]::InvariantCulture )
if ( $n -ne -1 ) {
$newmodel = ( "{0}{1}" -f $newmodel.Substring( 0, $n ), $newmodel.Substring( $n + 1 ) )
# Remove first lower case "e" and trailing whitespace following removed "n"
$e = $newmodel.IndexOf( 'e', $n, [System.StringComparison]::InvariantCulture )
if ( $e -ne -1 ) {
$newmodel = ( "{0}{1}" -f $newmodel.Substring( 0, $e ), $newmodel.Substring( $e + 1 ).Trim( ) )
$Model = $newmodel
}
}
}
}
}
}
$found = $true
"{0}`t`t{1}" -f $Registration, $Model
}
}
}
if ( $Debug ) {
Write-Host ( "Finished at {0} (elapsed time {1})`n`n" -f ( Get-Date ), $StopWatch.Elapsed )
$StopWatch.Stop( )
}
} else {
# No database text file found
if ( $Quiet ) {
if ( $Debug ) {
Write-Host ( "Downloaded Lithuanian aircraft register database file `"{0}`" not found" -f $dbfile )
}
exit 1
} else {
$message = "No downloaded Lithuanian aircraft register database was found.`n`nDo you want to open the download webpage for the database now?"
$title = 'No Database Found'
$buttons = 'YesNo'
Add-Type -AssemblyName System.Windows.Forms
$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
if ( $answer -eq "Yes" ) {
$url = 'https://tka.lt/oro-transportas/katalogas/register-of-civil-aircraft-of-the-republic-of-lithuania/?lang=en'
Start-Process $url
} else {
ShowHelp( 'No downloaded Lithuanian aircraft register database found, please download it and try again' )
}
}
}
page last modified: 2024-04-16; loaded in 0.0150 seconds