Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for airregeicmd.ps

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

  1. <#
  2. .SYNOPSIS
  3. Search a downloaded Irish aircraft registration database for a Irish aircraft registation and if found, return the aircraft manufacturer and model (tab-delimited)
  4.  
  5. .DESCRIPTION
  6. First, create a subdirectory 'EI' in this script's parent folder.
  7. Next, download the Irish aircraft registration database (see links section), unzip it and move the Excel file (and optionally the other files as well) to the 'EI' folder.
  8. Now run this script with an aircraft registration as its only parameter (see examples section).
  9. The script will first look for the most recent Excel file in the 'EI' folder.
  10. When found, it will open the first sheet of the Excel file, and search for the specified aircraft registration in the first column of the Excel sheet.
  11. If a match is found, the script will display a tab-delimited string with the registration, the manufacturer and the aircraft model (<registration><tab><manufacturer><tab><model>).
  12. 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.
  13. 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.
  14. Get-Help './AirRegEICmd.ps1' -Examples will show 2 examples of this script being called by another script.
  15.  
  16. .PARAMETER Registration
  17. A valid Irish aircraft registration, i.e. EI-xxx (where x is a single character)
  18.  
  19. .PARAMETER TerminateExcel
  20. Terminate Excel when the script is finished, if and only if Excel was not running when the script was started and the number of Excel processes is exactly one when the script is finished.
  21.  
  22. .PARAMETER Quiet
  23. Ignore all errors and do not display any error messages; in case of errors, just terminate with return code 1.
  24.  
  25. .PARAMETER Debug
  26. Show some progress messages
  27.  
  28. .PARAMETER Help
  29. Show the script's help screen
  30.  
  31. .OUTPUTS
  32. A tab-delimited string <registration><tab><manufacturer><tab><model> and manufacturer and model are also stored in output variables $Manufacturer and $Model.
  33.  
  34. .EXAMPLE
  35. . ./AirRegEICmd.ps1 "EI-ALP"
  36. Will return tab-delimited string "EI-ALP<tab>BAE SYSTEMS (OPERATIONS) LIMITED<tab>AVRO 643 CADET", and set variables $Manufacturer to "BAE SYSTEMS (OPERATIONS) LIMITED" and $Model to "AVRO 643 CADET"
  37.  
  38. .EXAMPLE
  39. "EI-ALP" | . ./AirRegEICmd.ps1
  40. Will also return tab-delimited string "EI-ALP<tab>BAE SYSTEMS (OPERATIONS) LIMITED<tab>AVRO 643 CADET", and set variables $Manufacturer to "BAE SYSTEMS (OPERATIONS) LIMITED" and $Model to "AVRO 643 CADET"
  41.  
  42. .EXAMPLE
  43. Create and run the following PowerShell script:
  44. ===============================================================
  45. $Registration = 'EI-ALP' ; $Manufacturer = '' ; $Model = ''
  46. [void] ( . "$PSScriptRoot\AirRegEICmd.ps1" -Registration $Registration )
  47. Write-Host ( "Registration : {0}`nManufacturer : {1}`nModel        : {2}" -f $Registration, $Manufacturer, $Model )
  48. ===============================================================
  49.  
  50. Besides setting variables $Manufacturer to "HiSystems GmbH" and $Model to "MK OktoKopter XL2", it will return:
  51.  
  52. Registration : EI-ALP
  53. Manufacturer : BAE SYSTEMS (OPERATIONS) LIMITED
  54. Model        : AVRO 643 CADET
  55.  
  56. .EXAMPLE
  57. Create and run the following batch file:
  58. ===============================================================
  59. REM Note that there should only be a TAB and nothing else between delims= and the doublequote
  60. FOR /F "tokens=1-3 delims=	" %%A IN ('powershell . ./AirRegEICmd.ps1 EI-ALP') DO (
  61. 	ECHO Registration : %%A
  62. 	ECHO Manufacturer : %%B
  63. 	ECHO Model        : %%C
  64. )
  65. ===============================================================
  66.  
  67. It will return:
  68.  
  69. Registration : EI-ALP
  70. Manufacturer : BAE SYSTEMS (OPERATIONS) LIMITED
  71. Model        : AVRO 643 CADET
  72.  
  73. .LINK
  74. Script written by Rob van der Woude:
  75. https://www.robvanderwoude.com/
  76.  
  77. .LINK
  78. Downloadable Irish aircraft registration database in Excel format:
  79. https://www.iaa.ie/commercial-aviation/aircraft-registration-2/latest-register-and-monthly-changes-1
  80.  
  81. .LINK
  82. Article "PowerShell - Read an Excel file using COM Interface" by François-Xavier Cat:
  83. https://lazywinadmin.com/2014/03/powershell-read-excel-file-using-com.html
  84. #>
  85.  
  86. param (
  87. 	[Parameter( ValueFromPipeline )]
  88. 	[ValidatePattern("(^\s*$|[\?/]|^EI-[A-Z]{3}$)")]
  89. 	[string]$Registration,
  90. 	[switch]$TerminateExcel,
  91. 	[switch]$Quiet,
  92. 	[switch]$Help
  93. )
  94.  
  95. $progver = "1.00"
  96.  
  97. $Registration = $Registration.ToUpper( )
  98. $Manufacturer = ''
  99. $Model = ''
  100. $ExcelError = $false
  101. [bool]$Debug = ( $PSBoundParameters.ContainsKey( 'Debug' ) )
  102.  
  103. function GetMonth( ) {
  104. 	param (
  105. 		[Parameter(Mandatory)]
  106. 		[ValidateSet("january","february","march","april","may","june","july","august","september","october","november","december")]
  107. 		[string]
  108. 		$month
  109. 	)
  110.  
  111. 	( "","january","february","march","april","may","june","july","august","september","october","november","december" ).IndexOf( $month.ToLower( ) )
  112. }
  113.  
  114. function GetLatestExcelFile( $folder ) {
  115. 	[string]$excelfile = ''
  116. 	[int]$latestyear = 0
  117. 	[int]$latestmonth = 0
  118. 	[int]$latestday = 0
  119. 	Get-ChildItem -Path $dbfolder -Filter '*-*-*.xlsx' | ForEach-Object {
  120. 		$filename = $_.BaseName
  121. 		$filedate = $filename.Split( '-' )
  122. 		# Initially selected file is the first one
  123. 		if ( $excelfile -eq '' ) {
  124. 			$excelfile = $_.FullName
  125. 			$latestyear = $filedate[2]
  126. 			$latestmonth = ( GetMonth( $filedate[1] ) )
  127. 			$latestday = $filedate[0]
  128. 		}
  129. 		# Next we'll look for a more recently released file
  130. 		if ( $filedate[2] -gt $latestyear ) {
  131. 			$excelfile = $_.FullName
  132. 			$latestyear = $filedate[2]
  133. 			$latestmonth = ( GetMonth( $filedate[1] ) )
  134. 			$latestday = $filedate[0]
  135. 		} elseif ( $filedate[2] -eq $latestyear ) {
  136. 			if ( ( GetMonth( $filedate[1] ) ) -gt $latestmonth ) {
  137. 				$excelfile = $_.FullName
  138. 				$latestyear = $filedate[2]
  139. 				$latestmonth = ( GetMonth( $filedate[1] ) )
  140. 				$latestday = $filedate[0]
  141. 			}
  142. 		}
  143. 	}
  144. 	$excelfile
  145. }
  146.  
  147. function ShowHelp( $errormessage = '' ) {
  148. 	if ( !$Quiet ) {
  149. 		if ( $errormessage ) {
  150. 			Write-Host
  151. 			Write-Host "Error: " -ForegroundColor Red -NoNewline
  152. 			Write-Host $errormessage
  153. 		}
  154. 		Write-Host
  155. 		Write-Host ( "AirRegEICmd.ps1,  Version {0}" -f $progver )
  156. 		Write-Host "Search downloaded Irish aircraft registration database for a registation"
  157. 		Write-Host
  158. 		Write-Host "Usage:  " -NoNewline
  159. 		Write-Host ". ./AirRegEICmd.ps1  [ -Registration ]  EI-***  [ -TerminateExcel ]  [ -Help ]" -ForegroundColor White
  160. 		Write-Host
  161. 		Write-Host "Where:  " -NoNewline
  162. 		Write-Host "EI-***           " -NoNewline -ForegroundColor White
  163. 		Write-Host "is a valid Irish aircraft registration, e.g. EI-ALP"
  164. 		Write-Host "        -TerminateExcel  " -NoNewline -ForegroundColor White
  165. 		Write-Host "terminates Excel when the script is finished, " -NoNewline
  166. 		Write-Host "if " -NoNewline -ForegroundColor White
  167. 		Write-Host "and " -NoNewline
  168. 		Write-Host "only" -ForegroundColor White
  169. 		Write-Host "                         if " -NoNewline -ForegroundColor White
  170. 		Write-Host "Excel was not running when the script was started"
  171. 		Write-Host "        -Quiet           " -NoNewline -ForegroundColor White
  172. 		Write-Host "all errors are ignored and no error messages displayed"
  173. 		Write-Host "        -Help            " -NoNewline -ForegroundColor White
  174. 		Write-Host "shows this help screen"
  175. 		Write-Host
  176. 		Write-Host "Notes:  This script requires a downloaded Irish aircraft registration database,"
  177. 		Write-Host "        located in a subfolder 'EI' of this script's parent folder."
  178. 		Write-Host "        The Irish aircraft registration database can be downloaded at:"
  179. 		Write-Host "        https://www.iaa.ie/commercial-aviation/aircraft-registration-2" -ForegroundColor DarkGray
  180. 		Write-Host "        /latest-register-and-monthly-changes-1" -ForegroundColor DarkGray
  181. 		Write-Host "        This script also requires Excel, since the downloaded database is in"
  182. 		Write-Host "        Excel format."
  183. 		Write-Host "        The result, if any, of the search is displayed as tab-delimited text:"
  184. 		Write-Host "        <registration><tab><manufacturer><tab><model>"
  185. 		Write-Host "        Besides its screen output, this script will also set the `$Manufacturer"
  186. 		Write-Host "        and `$Model variables with the database search result."
  187. 		Write-Host "        Run " -NoNewline
  188. 		Write-Host "Get-Help `"./AirRegEICmd.ps1`" -Examples " -NoNewline -ForegroundColor White
  189. 		Write-Host "for some examples of"
  190. 		Write-Host "        `"nesting`" this script in other PowerShell or batch scripts."
  191. 		Write-Host "        Return code (`"ErrorLevel`") 1 in case of errors, otherwise 0."
  192. 		Write-Host
  193. 		Write-Host "Written by Rob van der Woude"
  194. 		Write-Host "https://www.robvanderwoude.com"
  195. 	}
  196. 	Exit 1
  197. }
  198.  
  199. if ( $Help -or $Registration -match "(^\s*$|^-|\?|/)" ) {
  200. 	ShowHelp
  201. 	Exit 1
  202. }
  203.  
  204. # Check if Excel is already running
  205. $excelactive = [bool]( ( Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Measure-Object ).Count -gt 0 )
  206. if ( $Debug ) {
  207. 	if ( $excelactive ) {
  208. 		Write-Host "Excel already active at start"
  209. 	} else {
  210. 		Write-Host "Excel not active at start"
  211. 	}
  212. }
  213.  
  214. $dbfolder = ( Join-Path -Path $PSScriptRoot -ChildPath 'EI' )
  215. if ( Test-Path $dbfolder ) {
  216. 	$excelfile = GetlatestExcelFile( $dbfolder )
  217. 	if ( $excelfile ) {
  218. 		if ( $Debug ) {
  219. 			Write-Host ( "Using Excel file `"{0}`"" -f $excelfile )
  220. 			$StopWatch = [System.Diagnostics.Stopwatch]::StartNew( )
  221. 			Write-Host ( "Start searching for {0} in Excel file at {1}" -f $Registration, ( Get-Date ) )
  222. 		}
  223. 		$found = $false # will be set to True when a matching aircraft is found in the database
  224. 		$ErrorActionPreference = 'SilentlyContinue' # Temporarily hide all error messages, we will handle the next one ourselves
  225. 		# Open an Excel COM object
  226. 		$objExcel = New-Object -ComObject Excel.Application -ErrorAction 'SilentlyContinue' -ErrorVariable ExcelError
  227. 		$ErrorActionPreference = 'Continue' # Reenable output of future error messages
  228. 		if ( $ExcelError ) {
  229. 			ShowHelp( "Microsoft Excel not found" ) # Actually we were unable to open Excel's COM object
  230. 		} else {
  231. 			$ErrorActionPreference = 'SilentlyContinue' # Temporarily hide all error messages, we will handle the next one ourselves
  232. 			# Open the Excel aircraft database file
  233. 			$workbook = $objExcel.Workbooks.Open( $excelfile )
  234. 			$ErrorActionPreference = 'Continue' # Reenable output of future error messages
  235. 			# Check if the Excel file was successfully opened
  236. 			if ( ![bool]( $objExcel.WorkBooks | Select-Object -Property Name ) ) {
  237. 				$ErrorActionPreference = 'SilentlyContinue' # Ignore possible error when trying to close the Excel file and program
  238. 				[void] $workbook.Close( )
  239. 				[void] $objExcel.Quit( )
  240. 				$ErrorActionPreference = 'Continue' # Reenable output of future error messages
  241. 				ShowHelp( "Unable to open Excel file `"{0}`"" -f $excelfile )
  242. 			}
  243. 			# Iterate through all rows in the first sheet of the Excel file
  244. 			$workbook.Sheets.Item( 1 ).UsedRange.Rows | ForEach-Object {
  245. 				# After the first match we don't need to check for other matches, hence the check of the $found variable
  246. 				if ( !$found ) {
  247. 					if ( $_.Columns.Item( 1 ).Text -eq $Registration ) {
  248. 						# We have a match!
  249. 						if ( $Debug ) {
  250. 							Write-Host ( "Found a match at {0}" -f ( Get-Date ) )
  251. 						}
  252. 						$found = $true # used instead of Break, which would also stop parent process; only slightly slower than Break
  253. 						$Manufacturer = $_.Columns.Item( 2 ).Text # Manufacturer is in column B
  254. 						$Model = $_.Columns.Item( 3 ).Text # Model is in column C
  255. 						# By not using Write-Host, we allow calling scripts to suppress screen output and use passed on global variables
  256. 						( "{0}`t{1}`t{2}" -f $_.Columns.Item( 1 ).Text, $Manufacturer, $Model ) | Out-String
  257. 					}
  258. 				}
  259. 			}
  260. 			[void] $workbook.Close( )
  261. 			[void] $objExcel.Quit( )
  262. 			if ( $Debug ) {
  263. 				Write-Host ( "Finished at {0} (elapsed time {1})" -f ( Get-Date ), $StopWatch.Elapsed )
  264. 				$StopWatch.Stop( )
  265. 			}
  266. 		}
  267. 	} else {
  268. 		if ( $Debug ) {
  269. 			Write-Host ( "Database folder `"{0}`" not found" -f $dbfolder )
  270. 		}
  271. 		if ( $Quiet ) {
  272. 			Exit 1
  273. 		} else {
  274. 			$message = "No downloaded Irish aircraft registration database was found.`n`nDo you want to open the download webpage for the database now?"
  275. 			$title   = "No Database Found"
  276. 			$buttons = "YesNo"
  277. 			Add-Type -AssemblyName 'System.Windows.Forms'
  278. 			$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
  279. 			if ( $answer -eq 'Yes' ) {
  280. 				$url = 'https://www.iaa.ie/commercial-aviation/aircraft-registration-2/latest-register-and-monthly-changes-1'
  281. 				Start-Process $url
  282. 			} else {
  283. 				ShowHelp( "No downloaded Irish aircraft registration database found, please download it and try again" )
  284. 			}
  285. 		}
  286. 	}
  287. }
  288.  
  289. # Terminate Excel if requested and if this script's Excel process was the only instance
  290. $processcount = ( Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Measure-Object ).Count
  291. if ( $Debug ) {
  292. 	Write-Host ( "{0} active Excel processes when done" -f $processcount )
  293. }
  294. if ( $TerminateExcel -and !$excelactive -and ( $processcount -eq 1 ) ) {
  295. 	if ( $Debug ) {
  296. 		Write-Host "Terminating Excel now"
  297. 	}
  298. 	Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Stop-Process -ErrorAction 'SilentlyContinue'
  299. }
  300.  

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