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 inatllation 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. . ./AirRegTFmd.ps1 -Version -Verbose
  63. Will return the full script path, version and last modified/release date
  64.  
  65. .EXAMPLE
  66. . ./AirRegTFmd.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.00"
  132.  
  133. $Registration = $Registration.ToUpper( )
  134. [string]$Manufacturer = ''
  135. [string]$Model = ''
  136. [bool]$Debug = ( $PSBoundParameters.ContainsKey( 'Debug' ) )
  137.  
  138. function ShowHelp( $errormessage = '' ) {
  139. 	if ( !$Quiet ) {
  140. 		if ( $errormessage ) {
  141. 			Write-Host
  142. 			Write-Host "Error: " -ForegroundColor Red -NoNewline
  143. 			Write-Host $errormessage
  144. 		}
  145. 		Write-Host
  146. 		Write-Host ( "AirRegOECmd.ps1,  Version {0}" -f $progver )
  147. 		Write-Host "Search downloaded Austrian aircraft register database for a registation"
  148. 		Write-Host
  149. 		Write-Host "Usage:  " -NoNewline
  150. 		Write-Host ". ./AirRegOECmd.ps1 [ -Registration ] OE-*** [ switches ]" -ForegroundColor White
  151. 		Write-Host
  152. 		Write-Host "Where:    " -NoNewline
  153. 		Write-Host "OE-***          " -NoNewline -ForegroundColor White
  154. 		Write-Host "is a valid Austrian aircraft registration, e.g. OE-AKJ"
  155. 		Write-Host
  156. 		Write-Host "Switches: -ConvertPDF     " -NoNewline -ForegroundColor White
  157. 		Write-Host "force conversion of new PDF to plain text (use after"
  158. 		Write-Host "                          downloading a new PDF file)"
  159. 		Write-Host "          -Quiet          " -NoNewline -ForegroundColor White
  160. 		Write-Host "all errors are ignored and no error messages displayed"
  161. 		Write-Host "          -Debug          " -NoNewline -ForegroundColor White
  162. 		Write-Host "shows some progress messages"
  163. 		Write-Host "          -Help           " -NoNewline -ForegroundColor White
  164. 		Write-Host "shows this help screen"
  165. 		Write-Host "          -Version        " -NoNewline -ForegroundColor White
  166. 		Write-Host "show this script's version number; if combined with"
  167. 		Write-Host "                          -Verbose " -NoNewline -ForegroundColor White
  168. 		Write-Host "show full script path, version number and"
  169. 		Write-Host "                          last/modified/release date"
  170. 		Write-Host
  171. 		Write-Host "Notes:    This script requires a downloaded Austrian aircraft register database,"
  172. 		Write-Host "          located in a subfolder 'OE' of this script's parent folder."
  173. 		Write-Host "          The Austrian aircraft register database can be downloaded at:"
  174. 		Write-Host "          https://www.austrocontrol.at/en/aviation_agency" -ForegroundColor DarkGray
  175. 		Write-Host "          /aircraft/aircraft_register/overview__supplement" -ForegroundColor DarkGray
  176. 		Write-Host "          The first time this script runs, or when the " -NoNewline
  177. 		Write-Host "-ConvertPDF " -NoNewline -ForegroundColor White
  178. 		Write-Host "switch is"
  179. 		Write-Host "          used, it will try to convert the most recent PDF aircraft registry"
  180. 		Write-Host "          file to plain text using GhostScript; if neither GhostScript nor"
  181. 		Write-Host "          the converted text file is found, the script will abort; in that"
  182. 		Write-Host "          case, either download and install GhostScript or convert the PDF"
  183. 		Write-Host "          file with GhostScript on another computer, and then try again."
  184. 		Write-Host "          GhostScript for Windows can be downloaded at:"
  185. 		Write-Host "          https://www.ghostscript.com/download/gsdnld.html" -ForegroundColor DarkGray
  186. 		Write-Host "          The result, if any, of the search is displayed as tab-delimited text:"
  187. 		Write-Host "          <registration><tab><manufacturer><tab><model>"
  188. 		Write-Host "          Besides its screen output, this script will also set the `$Manufacturer"
  189. 		Write-Host "          and `$Model variables with the database search result."
  190. 		Write-Host "          Run " -NoNewline
  191. 		Write-Host "Get-Help `"./AirRegOECmd.ps1`" -Examples " -NoNewline -ForegroundColor White
  192. 		Write-Host "for some examples of"
  193. 		Write-Host "          `"nesting`" this script in other PowerShell or batch scripts."
  194. 		Write-Host "          Return code (`"ErrorLevel`") 1 in case of errors, otherwise 0."
  195. 		Write-Host
  196. 		Write-Host "Credits:  Command to convert PDF to text by user2176753 on StackOverflow.com:"
  197. 		Write-Host "          https://stackoverflow.com/a/26405241" -ForegroundColor DarkGray
  198. 		Write-Host "          Code to capture common parameters by mklement0 on StackOverflow.com:"
  199. 		Write-Host "          https://stackoverflow.com/a/48643616" -ForegroundColor DarkGray
  200. 		Write-Host
  201. 		Write-Host "Written by Rob van der Woude"
  202. 		Write-Host "https://www.robvanderwoude.com"
  203. 	}
  204. 	exit 1
  205. }
  206.  
  207. if ( $Help -or $Registration -match '(^\s*$|[\?/])' ) {
  208. 	ShowHelp
  209. 	exit 1
  210. }
  211.  
  212. function GetGhostscript( ) {
  213. 	# Check if GhostScript is installed, and if so, return the path to the command line execuatable
  214. 	$gskey = $null
  215. 	$gspath = ''
  216. 	$gsprog = ''
  217. 	if ( $Debug ) {
  218. 		Write-Host ( "Start searching the registry for GhostScript installations at {0}" -f ( Get-Date ) )
  219. 	}
  220. 	$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
  221. 	if ( $gskey ) {
  222. 		if ( $Debug ) {
  223. 			Write-Host ( "Found GhostScript installation in the registry: `"{0}`" at {1}" -f $gskey, ( Get-Date ) )
  224. 		}
  225. 		$gspath = ( Get-ItemProperty -Path "Registry::$gskey" ).'(default)'
  226. 		if ( $gspath ) {
  227. 			if ( $Debug ) {
  228. 				Write-Host ( "Found GhostScript path in the registry: `"{0}`"" -f $gspath )
  229. 			}
  230. 			$gsprog = ( Get-ChildItem -Path "$gspath" -Filter 'gs*c.exe' -Recurse ).FullName
  231. 			if ( $Debug ) {
  232. 				Write-Host ( "Found GhostScript executable: `"{0}`"" -f $gsprog )
  233. 			}
  234. 		}
  235. 	}
  236. 	$gsprog
  237. }
  238.  
  239. function Convert-PDF2Text( [string]$pdffile, [string]$textfile = '' ) {
  240. 	if ( $Debug ) {
  241. 		Write-Host ( "Trying to convert downloaded PDF aircraft registry database file `"{0}`" to plain text at {1}" -f $pdffile, ( Get-Date ) )
  242. 		Write-Host "First, try and find GhostScript"
  243. 	}
  244. 	$gsexec = ( GetGhostScript )
  245. 	if ( [string]::IsNullOrWhiteSpace( $gsexec ) ) {
  246. 		if ( !$Quiet ) {
  247. 			Write-Host "GhostScript not found on this computer"
  248. 		}
  249. 		$false
  250. 	} else {
  251. 		if ( $Debug ) {
  252. 			Write-Host ( "GhostScript command line executable found: `"{0}`"" -f $gsexec )
  253. 		}
  254. 		if ( Test-Path -Path "$pdffile" -PathType 'Leaf' ) {
  255. 			if ( $Debug ) {
  256. 				Write-Host "PDF file found"
  257. 			}
  258. 			if ( [string]::IsNullOrWhiteSpace( $textfile ) ) {
  259. 				$parentfolder = [System.IO.Directory]::GetParent( $pdffile )
  260. 				$textfilename = [System.IO.Path]::GetFileNameWithoutExtension( $pdffile )
  261. 				$newtextfile = ( Join-Path -Path "$parentfolder" -ChildPath "$textfilename.txt" )
  262. 				$oldtextfile = ( Join-Path -Path "$parentfolder" -ChildPath "$textfilename.old" )
  263. 				if ( $Debug ) {
  264. 					Write-Host ( "New text file will be `"{0}`'" -f $newtextfile )
  265. 				}
  266. 				if ( Test-Path -Path "$newtextfile" -PathType 'Leaf' ) {
  267. 					if ( $debug ) {
  268. 						Write-Host "Text file already exist"
  269. 					}
  270. 					if ( Test-Path -Path $oldtextfile -PathType 'Leaf' ) {
  271. 						if ( $Debug ) {
  272. 							Write-Host ( "Deleting old text file `"{0}`"" -f $oldtextfile )
  273. 						}
  274. 						[System.IO.File]::Delete( $oldtextfile )
  275. 					}
  276. 					if ( $Debug ) {
  277. 						Write-Host ( "Renaming existing text file `"{0}`" to `"{1}`"" -f $newtextfile, $oldtextfile )
  278. 					}
  279. 					[System.IO.File]::Move( $newtextfile, $oldtextfile )
  280. 				}
  281. 			} else {
  282. 				$newtextfile = $textfile
  283. 				if ( $Debug ) {
  284. 					Write-Host ( "New text file will be `"{0}`'" -f $newtextfile )
  285. 				}
  286. 			}
  287. 			if ( $Debug ) {
  288. 				Write-Host ( "Actual conversion started at {0} using the command:" -f ( Get-Date ) )
  289. 				Write-Host "`"$gsexec`" -sDEVICE=txtwrite -o `"$newtextfile`" `"$pdffile`""
  290. 			}
  291. 			( . "$gsexec" -sDEVICE=txtwrite -o "$newtextfile" "$pdffile" )
  292. 			$true
  293. 		} else {
  294. 			if ( $Debug -or !$Quiet ) {
  295. 				Write-Host ( "Downloaded PDF aircraft registry database file `"{0}`" not found" -f $pdffile )
  296. 			}
  297. 			$false
  298. 		}
  299. 	}
  300. }
  301.  
  302. $OE_mark = $Registration.Substring( 3 )
  303.  
  304. $dbfile = ''
  305. $dbfolder = ( Join-Path -Path $PSScriptRoot -ChildPath 'OE' )
  306. if ( $Debug ) {
  307. 	$StopWatch = [System.Diagnostics.Stopwatch]::StartNew( )
  308. }
  309. if ( $ConvertPDF ) {
  310. 	$ErrorActionPreference = 'SilentlyContinue'
  311. 	$pdffile = ( Get-ChildItem -Path $dbfolder -Filter 'Gesamt_*_EN.pdf' | Sort-Object -Property 'Name' | Select-Object -Last 1 ).FullName
  312. 	$ErrorActionPreference = 'Continue'
  313. 	if ( $Debug ) {
  314. 		Write-Host "-ConvertPDF switch used, convert latest PDF to plain text first"
  315. 		Write-Host ( "Started search for local database (PDF format) in folder `"{0}`" at {1}" -f $dbfolder, ( Get-Date ) )
  316. 	}
  317. 	if ( Convert-PDF2Text $pdffile ) {
  318. 		$pdffilename = [System.IO.Path]::GetFileNameWithoutExtension( $pdffile )
  319. 		$dbfile = ( Join-Path -Path $dbfolder -ChildPath "$pdffilename.txt" )
  320. 	}
  321. } else {
  322. 	if ( $Debug ) {
  323. 		Write-Host ( "Started search for local database (text format) in folder `"{0}`" at {1}" -f $dbfolder, ( Get-Date ) )
  324. 	}
  325. 	$ErrorActionPreference = 'SilentlyContinue'
  326. 	$dbfile = ( Get-ChildItem -Path $dbfolder -Filter 'Gesamt_*_EN.txt' | Sort-Object -Property 'Name' | Select-Object -Last 1 ).FullName
  327. 	$ErrorActionPreference = 'Continue'
  328. }
  329. if ( [string]::IsNullOrWhiteSpace( $dbfile ) ) {
  330. 	if ( $Quiet -and !$Debug ) {
  331. 		exit 1
  332. 	} else {
  333. 		if ( $Debug ) {
  334. 			Write-Host "Converted text file not found, looking for original PDF aircraf registry database file"
  335. 		}
  336. 		$textfilename = [System.IO.Path]::GetFileNameWithoutExtension( $dbfile )
  337. 		$pdffile = ( Join-Path -Path $dbfolder -ChildPath "$textfilename.pdf" )
  338. 		if ( Test-Path $pdffile -PathType 'Leaf' ) {
  339. 			if ( $Debug ) {
  340. 				Write-Host ( "Founf PDF file `"{0}`"" -f $pdffile )
  341. 			}
  342. 			$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?"
  343. 			$title = "PDF to Text Conversion Required"
  344. 			$buttons = [System.Windows.Forms.MessageBoxButtons]::YesNo
  345. 			$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
  346. 			if ( $answer = 'Yes' ) {
  347. 				if ( Convert-PDF2Text $pdffile ) {
  348. 					if ( $Debug ) {
  349. 						Write-Host "PDF to text conversion completed"
  350. 					}
  351. 				} else {
  352. 					if ( $Debug -or !$Quiet ) {
  353. 						Write-Host "PDF to text conversion failed"
  354. 						exit 1
  355. 					}
  356. 				}
  357. 			} else {
  358. 				if ( $Debug -or !$Quiet ) {
  359. 					Write-Host "Please convert your PDF aircraft registry database file to plain text and try again"
  360. 				}
  361. 				exit 1
  362. 			}
  363. 		}
  364. 	}
  365. }
  366.  
  367. if ( $dbfile ) {
  368. 	if ( $Debug ) {
  369. 		Write-Host ( "Start searching {0} in {1} file at {1}" -f $OE_mark, $dbfile, ( Get-Date ) )
  370. 	}
  371. 	$pattern = "^\s{{16}}{0}\s" -f $OE_mark
  372. 	$found = $false
  373. 	( Get-Content -Path $dbfile ).Split( "`n" ) | ForEach-Object {
  374. 		if ( !$found ) {
  375. 			if ( $_ -match $pattern ) {
  376. 				if ( $Debug ) {
  377. 					Write-Host ( "Found a match at {0}" -f ( Get-Date ) )
  378. 				}
  379. 				$Manufacturer = $_.Substring( 40, 45 ).Trim( )
  380. 			} elseif ( ![string]::IsNullOrWhiteSpace( $Manufacturer ) ) {
  381. 				if ( $_.Length -gt 40 ) {
  382. 					if ( ![string]::IsNullOrWhiteSpace( $_.Substring( 40, [Math]::Min( 45, $_.Length - 40 ) ) ) ) {
  383. 						$Model = $_.Substring( 40, [Math]::Min( 45, $_.Length - 40 ) ).Trim( )
  384. 						$found = $true
  385. 						"{0}`t{1}`t{2}" -f $Registration, $Manufacturer, $Model
  386. 					}
  387. 				}
  388. 			}
  389. 		}
  390. 	}
  391. 	if ( $Debug ) {
  392. 		Write-Host ( "Finished at {0} (elapsed time {1})`n`n" -f ( Get-Date ), $StopWatch.Elapsed )
  393. 		$StopWatch.Stop( )
  394. 	}
  395. } else {
  396. 	# No database text file found
  397. 	if ( $Quiet ) {
  398. 		if ( $Debug ) {
  399. 			Write-Host ( "Downloaded Austrian aircraft register database file `"{0}`" not found" -f $dbfile )
  400. 		}
  401. 		exit 1
  402. 	} else {
  403. 		$message = "No downloaded Austrian aircraft register database was found.`n`nDo you want to open the download webpage for the database now?"
  404. 		$title   = 'No Database Found'
  405. 		$buttons = 'YesNo'
  406. 		Add-Type -AssemblyName System.Windows.Forms
  407. 		$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
  408. 		if ( $answer -eq "Yes" ) {
  409. 			$url = 'https://www.austrocontrol.at/en/aviation_agency/aircraft/aircraft_register/overview__supplement'
  410. 			Start-Process $url
  411. 		} else {
  412. 			ShowHelp( 'No downloaded Austrian aircraft register database found, please download it and try again' )
  413. 		}
  414. 	}
  415. }
  416.  

page last uploaded: 2019-01-21, 22:48