Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for airregoecmd.ps

(view source code of airregoecmd.ps as plain text)

  1. <#
  2. .SYNOPSIS
  3. Search a downloaded Austrian aircraft register database for an aircraft registation and if found, return the aircraft manufacturer and model (tab-delimited)
  4.  
  5. .DESCRIPTION
  6. First, create a subdirectory 'OE' in this script's parent folder.
  7. Next, download the Austrian aircraft register database (see links section), unzip it and move the PDF file to the 'OE' folder.
  8. Now run this script with an aircraft registration as its only parameter (see examples section).
  9. The script cannot read the PDF file directly, so the PDF file needs to be converted to plain text first.
  10. 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:
  11.  
  12. "C:\Program Files\gs\gs<version>\bin\gswin64c.exe" -sDEVICE=txtwrite -o Gesamt_<year>_EN.txt Gesamt_<year>_EN.pdf
  13.  
  14. 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!
  15.  
  16. After removing "OE-" from the registration, the script will search for a line that starts with the remainder of the registration.
  17. If a match is found, the manufacturer will be in the same line, more to the right, and the model will be on the next line right below the manufacturer.
  18. The script will display a tab-delimited string with the registration, the manufacturer and the aircraft model (<registration><tab><manufacturer><tab><model>).
  19. If the script was started by another PowerShell script, the calling PowerShell script may also read the manufacturer and model from the variables $Manufacturer and $Model, passed on by this script.
  20. 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 manufacturer and model.
  21. Get-Help './AirRegOECmd.ps1' -Examples will show 2 examples of this script being called by another script.
  22.  
  23. .PARAMETER Registration
  24. A valid Austrian aircraft registration, i.e. OE-xxx (where each x is a single character)
  25.  
  26. .PARAMETER ConvertPDF
  27. Force conversion of the latest PDF file to plain text; use this switch once after downloading a new PDF file.
  28.  
  29. .PARAMETER Quiet
  30. Ignore all errors and do not display any error messages; in case of errors, just terminate with return code 1.
  31.  
  32. .PARAMETER Help
  33. Show the script's help screen
  34.  
  35. .PARAMETER Version
  36. Show this script's version number; if combined with -Verbose show full script path, version number and last/modified/release date
  37.  
  38. .PARAMETER Debug
  39. Show some progress messages
  40.  
  41. .OUTPUTS
  42. A tab-delimited string <registration><tab><manufacturer><tab><model> and manufacturer and model are also stored in output variables $Manufacturer and $Model.
  43.  
  44. .EXAMPLE
  45. . ./AirRegOECmd.ps1 "OE-AKJ"
  46. Will return tab-delimited string "OE-AKJ<tab>Boeing Commercial Airplane Group<tab>E75", and set variables $Manufacturer to "BOEING" and $Model to "E75N1"
  47.  
  48. .EXAMPLE
  49. "OE-AKJ" | . ./AirRegOECmd.ps1
  50. Will also return tab-delimited string "OE-AKJ<tab>Boeing Commercial Airplane Group<tab>E75", and set variables $Manufacturer to "BOEING" and $Model to "E75N1"
  51.  
  52. .EXAMPLE
  53. . ./AirRegOECmd.ps1 "OE-AKJ" -Debug
  54. This will return:
  55.  
  56. Start searching AHA in carscurr.txt file at <date> <time>
  57. OE-AKJ   Boeing Commercial Airplane Group  E75
  58.  
  59. Finished at <date> <time> (elapsed time <time elapsed>)
  60.  
  61. .EXAMPLE
  62. . ./AirRegOECmd.ps1 -Version -Verbose
  63. Will return the full script path, version and last modified/release date
  64.  
  65. .EXAMPLE
  66. . ./AirRegOECmd.ps1 -Version
  67. Will return the script version
  68.  
  69. .EXAMPLE
  70. Create and run the following PowerShell script:
  71. ===============================================================
  72. $Registration = 'OE-AKJ' ; $Manufacturer = '' ; $Model = ''
  73. [void] ( . "$PSScriptRoot\AirRegOECmd.ps1" -Registration $Registration )
  74. Write-Host ( "Registration : {0}`nManufacturer : {1}`nModel        : {2}" -f $Registration, $Manufacturer, $Model )
  75. ===============================================================
  76.  
  77. Besides setting variables $Manufacturer to "BOEING" and $Model to "E75", it will return:
  78.  
  79. Registration : OE-AKJ
  80. Manufacturer : Boeing Commercial Airplane Group
  81. Model        : E75
  82.  
  83. .EXAMPLE
  84. Create and run the following batch file:
  85. ===============================================================
  86. REM Note that there should only be a TAB and nothing else between delims= and the doublequote
  87. FOR /F "tokens=1-3 delims=	" %%A IN ('powershell . ./AirRegOECmd.ps1 OE-AKJ') DO (
  88. 	ECHO Registration : %%A
  89. 	ECHO Manufacturer : %%B
  90. 	ECHO Model        : %%C
  91. )
  92. ===============================================================
  93.  
  94. It will return:
  95.  
  96. Registration : OE-AKJ
  97. Manufacturer : Boeing Commercial Airplane Group
  98. Model        : E75
  99.  
  100. .LINK
  101. Script written by Rob van der Woude:
  102. https://www.robvanderwoude.com/
  103.  
  104. .LINK
  105. Austrian aircraft register database:
  106. https://www.austrocontrol.at/en/aviation_agency/aircraft/aircraft_register/overview__supplement
  107.  
  108. .LINK
  109. GhostScript download page:
  110. https://www.ghostscript.com/download/gsdnld.html
  111.  
  112. .LINK
  113. Convert PDF to text by user2176753 on StackOverflow.com:
  114. https://stackoverflow.com/a/26405241
  115.  
  116. .LINK
  117. Capture -Debug parameter by mklement0 on StackOverflow.com:
  118. https://stackoverflow.com/a/48643616
  119. #>
  120.  
  121. param (
  122. 	[parameter( ValueFromPipeline )]
  123. 	[ValidatePattern("(^\s*$|[\?/]|^OE-[A-Z]{3}$)")]
  124. 	[string]$Registration,
  125. 	[switch]$ConvertPDF,
  126. 	[switch]$Quiet,
  127. 	[switch]$Help,
  128. 	[switch]$Version
  129. )
  130.  
  131. $progver = "1.01"
  132.  
  133. $Registration = $Registration.ToUpper( )
  134. [string]$Manufacturer = ''
  135. [string]$Model = ''
  136. [bool]$Debug = ( $PSBoundParameters.ContainsKey( 'Debug' ) )
  137. [bool]$Verbose = ( $PSBoundParameters.ContainsKey( 'Verbose' ) )
  138.  
  139. if ( $Version ) {
  140. 	if ( $Verbose ) {
  141. 		$lastmod = ( [System.IO.File]::GetLastWriteTime( $PSCommandPath ) )
  142. 		if ( $lastmod.ToString( "h.mm" ) -eq $progver ) {
  143. 			"`"{0}`", Version {1}, release date {2}" -f $PSCommandPath, $progver, $lastmod.ToString( "yyyy-MM-dd" )
  144. 		} else {
  145. 			# if last modified time is not equal to program version, the script has been tampered with
  146. 			"`"{0}`", Version {1}, last modified date {2}" -f $PSCommandPath, $progver, $lastmod.ToString( "yyyy-MM-dd" )
  147. 		}
  148. 	} else {
  149. 		$progver
  150. 	}
  151. 	exit 0
  152. }
  153.  
  154. function ShowHelp( $errormessage = '' ) {
  155. 	if ( !$Quiet ) {
  156. 		Clear-Host
  157. 		if ( $errormessage ) {
  158. 			Write-Host
  159. 			Write-Host "Error: " -ForegroundColor Red -NoNewline
  160. 			Write-Host $errormessage
  161. 		}
  162. 		Write-Host
  163. 		Write-Host ( "`"{0}`", Version {1}" -f $PSCommandPath, $progver ) -NoNewline
  164. 		$lastmod = ( [System.IO.File]::GetLastWriteTime( $PSCommandPath ) )
  165. 		if ( $lastmod.ToString( "h.mm" ) -eq $progver ) {
  166. 			Write-Host ", release date " -NoNewline
  167. 		} else {
  168. 			# if last modified time is not equal to program version, the script has been tampered with
  169. 			Write-Host ", last modified date " -NoNewline
  170. 		}
  171. 		Write-Host $lastmod.ToString( "yyyy-MM-dd" )
  172. 		Write-Host
  173. 		Get-Help $PSCommandPath -Full
  174. 	}
  175. }
  176.  
  177. if ( $Help -or $Registration -match '(^\s*$|[\?/])' ) {
  178. 	ShowHelp
  179. 	exit 1
  180. }
  181.  
  182. function GetGhostscript( ) {
  183. 	# Check if GhostScript is installed, and if so, return the path to the command line execuatable
  184. 	$gskey = $null
  185. 	$gspath = ''
  186. 	$gsprog = ''
  187. 	if ( $Debug ) {
  188. 		Write-Host ( "Start searching the registry for GhostScript installations at {0}" -f ( Get-Date ) )
  189. 	}
  190. 	$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
  191. 	if ( $gskey ) {
  192. 		if ( $Debug ) {
  193. 			Write-Host ( "Found GhostScript installation in the registry: `"{0}`" at {1}" -f $gskey, ( Get-Date ) )
  194. 		}
  195. 		$gspath = ( Get-ItemProperty -Path "Registry::$gskey" ).'(default)'
  196. 		if ( $gspath ) {
  197. 			if ( $Debug ) {
  198. 				Write-Host ( "Found GhostScript path in the registry: `"{0}`"" -f $gspath )
  199. 			}
  200. 			$gsprog = ( Get-ChildItem -Path "$gspath" -Filter 'gs*c.exe' -Recurse ).FullName
  201. 			if ( $Debug ) {
  202. 				Write-Host ( "Found GhostScript executable: `"{0}`"" -f $gsprog )
  203. 			}
  204. 		}
  205. 	}
  206. 	$gsprog
  207. }
  208.  
  209. function Convert-PDF2Text( [string]$pdffile, [string]$textfile = '' ) {
  210. 	if ( $Debug ) {
  211. 		Write-Host ( "Trying to convert downloaded PDF aircraft registry database file `"{0}`" to plain text at {1}" -f $pdffile, ( Get-Date ) )
  212. 		Write-Host "First, try and find GhostScript"
  213. 	}
  214. 	$gsexec = ( GetGhostScript )
  215. 	if ( [string]::IsNullOrWhiteSpace( $gsexec ) ) {
  216. 		if ( !$Quiet ) {
  217. 			Write-Host "GhostScript not found on this computer"
  218. 		}
  219. 		$false
  220. 	} else {
  221. 		if ( $Debug ) {
  222. 			Write-Host ( "GhostScript command line executable found: `"{0}`"" -f $gsexec )
  223. 		}
  224. 		if ( Test-Path -Path "$pdffile" -PathType 'Leaf' ) {
  225. 			if ( $Debug ) {
  226. 				Write-Host "PDF file found"
  227. 			}
  228. 			if ( [string]::IsNullOrWhiteSpace( $textfile ) ) {
  229. 				$parentfolder = [System.IO.Directory]::GetParent( $pdffile )
  230. 				$textfilename = [System.IO.Path]::GetFileNameWithoutExtension( $pdffile )
  231. 				$newtextfile = ( Join-Path -Path "$parentfolder" -ChildPath "$textfilename.txt" )
  232. 				$oldtextfile = ( Join-Path -Path "$parentfolder" -ChildPath "$textfilename.old" )
  233. 				if ( $Debug ) {
  234. 					Write-Host ( "New text file will be `"{0}`'" -f $newtextfile )
  235. 				}
  236. 				if ( Test-Path -Path "$newtextfile" -PathType 'Leaf' ) {
  237. 					if ( $debug ) {
  238. 						Write-Host "Text file already exist"
  239. 					}
  240. 					if ( Test-Path -Path $oldtextfile -PathType 'Leaf' ) {
  241. 						if ( $Debug ) {
  242. 							Write-Host ( "Deleting old text file `"{0}`"" -f $oldtextfile )
  243. 						}
  244. 						[System.IO.File]::Delete( $oldtextfile )
  245. 					}
  246. 					if ( $Debug ) {
  247. 						Write-Host ( "Renaming existing text file `"{0}`" to `"{1}`"" -f $newtextfile, $oldtextfile )
  248. 					}
  249. 					[System.IO.File]::Move( $newtextfile, $oldtextfile )
  250. 				}
  251. 			} else {
  252. 				$newtextfile = $textfile
  253. 				if ( $Debug ) {
  254. 					Write-Host ( "New text file will be `"{0}`'" -f $newtextfile )
  255. 				}
  256. 			}
  257. 			if ( $Debug ) {
  258. 				Write-Host ( "Actual conversion started at {0} using the command:" -f ( Get-Date ) )
  259. 				Write-Host "`"$gsexec`" -sDEVICE=txtwrite -o `"$newtextfile`" `"$pdffile`""
  260. 			}
  261. 			( . "$gsexec" -sDEVICE=txtwrite -o "$newtextfile" "$pdffile" )
  262. 			$true
  263. 		} else {
  264. 			if ( $Debug -or !$Quiet ) {
  265. 				Write-Host ( "Downloaded PDF aircraft registry database file `"{0}`" not found" -f $pdffile )
  266. 			}
  267. 			$false
  268. 		}
  269. 	}
  270. }
  271.  
  272. $OE_mark = $Registration.Substring( 3 )
  273.  
  274. $dbfile = ''
  275. $dbfolder = ( Join-Path -Path $PSScriptRoot -ChildPath 'OE' )
  276. if ( $Debug ) {
  277. 	$StopWatch = [System.Diagnostics.Stopwatch]::StartNew( )
  278. }
  279. if ( $ConvertPDF ) {
  280. 	$ErrorActionPreference = 'SilentlyContinue'
  281. 	$pdffile = ( Get-ChildItem -Path $dbfolder -Filter 'Gesamt_*_EN.pdf' | Sort-Object -Property 'Name' | Select-Object -Last 1 ).FullName
  282. 	$ErrorActionPreference = 'Continue'
  283. 	if ( $Debug ) {
  284. 		Write-Host "-ConvertPDF switch used, convert latest PDF to plain text first"
  285. 		Write-Host ( "Started search for local database (PDF format) in folder `"{0}`" at {1}" -f $dbfolder, ( Get-Date ) )
  286. 	}
  287. 	if ( Convert-PDF2Text $pdffile ) {
  288. 		$pdffilename = [System.IO.Path]::GetFileNameWithoutExtension( $pdffile )
  289. 		$dbfile = ( Join-Path -Path $dbfolder -ChildPath "$pdffilename.txt" )
  290. 	}
  291. } else {
  292. 	if ( $Debug ) {
  293. 		Write-Host ( "Started search for local database (text format) in folder `"{0}`" at {1}" -f $dbfolder, ( Get-Date ) )
  294. 	}
  295. 	$ErrorActionPreference = 'SilentlyContinue'
  296. 	$dbfile = ( Get-ChildItem -Path $dbfolder -Filter 'Gesamt_*_EN.txt' | Sort-Object -Property 'Name' | Select-Object -Last 1 ).FullName
  297. 	$ErrorActionPreference = 'Continue'
  298. }
  299. if ( [string]::IsNullOrWhiteSpace( $dbfile ) ) {
  300. 	if ( $Quiet -and !$Debug ) {
  301. 		exit 1
  302. 	} else {
  303. 		if ( $Debug ) {
  304. 			Write-Host "Converted text file not found, looking for original PDF aircraf registry database file"
  305. 		}
  306. 		$textfilename = [System.IO.Path]::GetFileNameWithoutExtension( $dbfile )
  307. 		$pdffile = ( Join-Path -Path $dbfolder -ChildPath "$textfilename.pdf" )
  308. 		if ( Test-Path $pdffile -PathType 'Leaf' ) {
  309. 			if ( $Debug ) {
  310. 				Write-Host ( "Founf PDF file `"{0}`"" -f $pdffile )
  311. 			}
  312. 			$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?"
  313. 			$title = "PDF to Text Conversion Required"
  314. 			$buttons = [System.Windows.Forms.MessageBoxButtons]::YesNo
  315. 			$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
  316. 			if ( $answer = 'Yes' ) {
  317. 				if ( Convert-PDF2Text $pdffile ) {
  318. 					if ( $Debug ) {
  319. 						Write-Host "PDF to text conversion completed"
  320. 					}
  321. 				} else {
  322. 					if ( $Debug -or !$Quiet ) {
  323. 						Write-Host "PDF to text conversion failed"
  324. 						exit 1
  325. 					}
  326. 				}
  327. 			} else {
  328. 				if ( $Debug -or !$Quiet ) {
  329. 					Write-Host "Please convert your PDF aircraft registry database file to plain text and try again"
  330. 				}
  331. 				exit 1
  332. 			}
  333. 		}
  334. 	}
  335. }
  336.  
  337. if ( $dbfile ) {
  338. 	if ( $Debug ) {
  339. 		Write-Host ( "Start searching {0} in {1} file at {1}" -f $OE_mark, $dbfile, ( Get-Date ) )
  340. 	}
  341. 	$pattern = "^\s{{16}}{0}\s" -f $OE_mark
  342. 	$found = $false
  343. 	( Get-Content -Path $dbfile ).Split( "`n" ) | ForEach-Object {
  344. 		if ( !$found ) {
  345. 			if ( $_ -match $pattern ) {
  346. 				if ( $Debug ) {
  347. 					Write-Host ( "Found a match at {0}" -f ( Get-Date ) )
  348. 				}
  349. 				$Manufacturer = $_.Substring( 40, 45 ).Trim( )
  350. 			} elseif ( ![string]::IsNullOrWhiteSpace( $Manufacturer ) ) {
  351. 				if ( $_.Length -gt 40 ) {
  352. 					if ( ![string]::IsNullOrWhiteSpace( $_.Substring( 40, [Math]::Min( 45, $_.Length - 40 ) ) ) ) {
  353. 						$Model = $_.Substring( 40, [Math]::Min( 45, $_.Length - 40 ) ).Trim( )
  354. 						$found = $true
  355. 						"{0}`t{1}`t{2}" -f $Registration, $Manufacturer, $Model
  356. 					}
  357. 				}
  358. 			}
  359. 		}
  360. 	}
  361. 	if ( $Debug ) {
  362. 		Write-Host ( "Finished at {0} (elapsed time {1})`n`n" -f ( Get-Date ), $StopWatch.Elapsed )
  363. 		$StopWatch.Stop( )
  364. 	}
  365. } else {
  366. 	# No database text file found
  367. 	if ( $Quiet ) {
  368. 		if ( $Debug ) {
  369. 			Write-Host ( "Downloaded Austrian aircraft register database file `"{0}`" not found" -f $dbfile )
  370. 		}
  371. 		exit 1
  372. 	} else {
  373. 		$message = "No downloaded Austrian aircraft register database was found.`n`nDo you want to open the download webpage for the database now?"
  374. 		$title   = 'No Database Found'
  375. 		$buttons = 'YesNo'
  376. 		Add-Type -AssemblyName System.Windows.Forms
  377. 		$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
  378. 		if ( $answer -eq "Yes" ) {
  379. 			$url = 'https://www.austrocontrol.at/en/aviation_agency/aircraft/aircraft_register/overview__supplement'
  380. 			Start-Process $url
  381. 		} else {
  382. 			ShowHelp( 'No downloaded Austrian aircraft register database found, please download it and try again' )
  383. 		}
  384. 	}
  385. }
  386.  

page last uploaded: 2021-01-27