Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for airregphcmd.ps

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

  1. <#
  2. .SYNOPSIS
  3. Search a downloaded Dutch aircraft registration database for a Dutch aircraft registation and if found, return the aircraft manufacturer and model (tab-delimited)
  4.  
  5. .DESCRIPTION
  6. First, create a subdirectory 'PH' in this script's parent folder.
  7. Next, download the Dutch aircraft registration database (see links section), unzip it and move the Excel file (and optionally the other files as well) to the 'PH' 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 'PH' 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 './AirRegPHCmd.ps1' -Examples will show 2 examples of this script being called by another script.
  15.  
  16. .PARAMETER Registration
  17. A valid Dutch aircraft registration, i.e. PH-nn .. PH-nnnn or PH-xxx (where n is a single numeric digit, and x is a single alphanumeric character/digit)
  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. . ./AirRegPHCmd.ps1 "PH-PBB"
  36. Will return tab-delimited string "PH-PBB<tab>Consolidated-Vultee Aircraft Corp., Stinson Division<tab>L-5B", and set variables $Manufacturer to "Consolidated-Vultee Aircraft Corp., Stinson Division" and $Model to "L-5B"
  37.  
  38. .EXAMPLE
  39. "PH-PBB" | . ./AirRegPHCmd.ps1
  40. Will also return tab-delimited string "PH-PBB<tab>Consolidated-Vultee Aircraft Corp., Stinson Division<tab>L-5B", and set variables $Manufacturer to "Consolidated-Vultee Aircraft Corp., Stinson Division" and $Model to "L-5B"
  41.  
  42. .EXAMPLE
  43. Create and run the following PowerShell script:
  44. ===============================================================
  45. $Registration = 'PH-1AE' ; $Manufacturer = '' ; $Model = ''
  46. [void] ( . "$PSScriptRoot\AirRegPHCmd.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 : PH-1AE
  53. Manufacturer : HiSystems GmbH
  54. Model        : MK OktoKopter XL2
  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 . ./AirRegPHCmd.ps1 PH-PBA') DO (
  61. 	ECHO Registration : %%A
  62. 	ECHO Manufacturer : %%B
  63. 	ECHO Model        : %%C
  64. )
  65. ===============================================================
  66.  
  67. It will return:
  68.  
  69. Registration : PH-PBA
  70. Manufacturer : Douglas Aircraft Company
  71. Model        : DC-3C-S1C3G               
  72.  
  73. .LINK
  74. Script written by Rob van der Woude:
  75. https://www.robvanderwoude.com/
  76.  
  77. .LINK
  78. Downloadable Dutch aircraft registration database in Excel format:
  79. https://www.ilent.nl/onderwerpen/luchtvaartuigregister/
  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*$|[\?/]|^PH-[0-9A-Z]{3}$|^PH-[0-9]{2,4}$)")]
  89. 	[string]$Registration,
  90. 	[switch]$TerminateExcel,
  91. 	[switch]$Quiet,
  92. 	[switch]$Help
  93. )
  94.  
  95. $progver = "1.03"
  96.  
  97. $Registration = $Registration.ToUpper( )
  98. $Manufacturer = ''
  99. $Model = ''
  100. $ExcelError = $false
  101. [bool]$Debug = ( $PSBoundParameters.ContainsKey( 'Debug' ) )
  102. [bool]$Verbose = ( $PSBoundParameters.ContainsKey( 'Verbose' ) )
  103.  
  104. if ( $Version ) {
  105. 	if ( $Verbose ) {
  106. 		$lastmod = ( [System.IO.File]::GetLastWriteTime( $PSCommandPath ) )
  107. 		if ( $lastmod.ToString( "h.mm" ) -eq $progver ) {
  108. 			"`"{0}`", Version {1}, release date {2}" -f $PSCommandPath, $progver, $lastmod.ToString( "yyyy-MM-dd" )
  109. 		} else {
  110. 			# if last modified time is not equal to program version, the script has been tampered with
  111. 			"`"{0}`", Version {1}, last modified date {2}" -f $PSCommandPath, $progver, $lastmod.ToString( "yyyy-MM-dd" )
  112. 		}
  113. 	} else {
  114. 		$progver
  115. 	}
  116. 	exit 0
  117. }
  118.  
  119. function ShowHelp( $errormessage = '' ) {
  120. 	if ( !$Quiet ) {
  121. 		Clear-Host
  122. 		if ( $errormessage ) {
  123. 			Write-Host
  124. 			Write-Host "Error: " -ForegroundColor Red -NoNewline
  125. 			Write-Host $errormessage
  126. 		}
  127. 		Write-Host
  128. 		Write-Host ( "`"{0}`", Version {1}" -f $PSCommandPath, $progver ) -NoNewline
  129. 		$lastmod = ( [System.IO.File]::GetLastWriteTime( $PSCommandPath ) )
  130. 		if ( $lastmod.ToString( "h.mm" ) -eq $progver ) {
  131. 			Write-Host ", release date " -NoNewline
  132. 		} else {
  133. 			# if last modified time is not equal to program version, the script has been tampered with
  134. 			Write-Host ", last modified date " -NoNewline
  135. 		}
  136. 		Write-Host $lastmod.ToString( "yyyy-MM-dd" )
  137. 		Write-Host
  138. 		Get-Help $PSCommandPath -Full
  139. 	}
  140. }
  141.  
  142. if ( $Help -or $Registration -match '(^\s*$|[\?/])' ) {
  143. 	ShowHelp
  144. 	exit 1
  145. }
  146.  
  147. # Check if Excel is already running
  148. $excelactive = [bool]( ( Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Measure-Object ).Count -gt 0 )
  149. if ( $Debug ) {
  150. 	if ( $excelactive ) {
  151. 		Write-Host "Excel already active at start"
  152. 	} else {
  153. 		Write-Host "Excel not active at start"
  154. 	}
  155. }
  156.  
  157. $dbfolder = ( Join-Path -Path $PSScriptRoot -ChildPath 'PH' )
  158. if ( Test-Path $dbfolder ) {
  159. 	$excelfile = ( Get-ChildItem -Path $dbfolder -Filter '* Aircraft registrations.xlsx' | Sort-Object $_.Name | Select-Object -Last 1 )
  160. 	if ( $excelfile ) {
  161. 		if ( $Debug ) {
  162. 			Write-Host ( "Using Excel file `"{0}`"" -f $excelfile.FullName )
  163. 			[System.Diagnostics.Stopwatch]::StartNew( )
  164. 			Write-Host ( "Start searching for {0} in Excel file at {1}" -f $Registration, ( Get-Date ) )
  165. 		}
  166. 		$found = $false # will be set to True when a matching aircraft is found in the database
  167. 		$ErrorActionPreference = 'SilentlyContinue' # Temporarily hide all error messages, we will handle the next one ourselves
  168. 		# Open an Excel COM object
  169. 		$objExcel = New-Object -ComObject Excel.Application -ErrorAction 'SilentlyContinue' -ErrorVariable ExcelError
  170. 		$ErrorActionPreference = 'Continue' # Reenable output of future error messages
  171. 		if ( $ExcelError ) {
  172. 			ShowHelp( "Microsoft Excel not found" ) # Actually we were unable to open Excel's COM object
  173. 		} else {
  174. 			$ErrorActionPreference = 'SilentlyContinue' # Temporarily hide all error messages, we will handle the next one ourselves
  175. 			# Open the Excel aircraft database file
  176. 			$workbook = $objExcel.Workbooks.Open( $excelfile.FullName )
  177. 			$ErrorActionPreference = 'Continue' # Reenable output of future error messages
  178. 			# Check if the Excel file was successfully opened
  179. 			if ( ![bool]( $objExcel.WorkBooks | Select-Object -Property Name ) ) {
  180. 				$ErrorActionPreference = 'SilentlyContinue' # Ignore possible error when trying to close the Excel file and program
  181. 				[void] $workbook.Close( )
  182. 				[void] $objExcel.Quit( )
  183. 				$ErrorActionPreference = 'Continue' # Reenable output of future error messages
  184. 				ShowHelp( "Unable to open Excel file `"{0}`"" -f $excelfile.FullName )
  185. 			}
  186. 			# Iterate through all rows in the first sheet of the Excel file
  187. 			$workbook.Sheets.Item( 1 ).UsedRange.Rows | ForEach-Object {
  188. 				# After the first match we don't need to check for other matches, hence the check of the $found variable
  189. 				if ( !$found ) {
  190. 					if ( $_.Columns.Item( 1 ).Text -eq $Registration ) {
  191. 						# We have a match!
  192. 						if ( $Debug ) {
  193. 							Write-Host ( "Found a match at {0}" -f ( Get-Date ) )
  194. 						}
  195. 						$found = $true # used instead of Break, which would also stop parent process; only slightly slower than Break
  196. 						$Manufacturer = $_.Columns.Item( 6 ).Text # Manufacturer is in column 6
  197. 						$Model = $_.Columns.Item( 8 ).Text # Model is in column 8
  198. 						# By not using Write-Host, we allow calling scripts to suppress screen output and use passed on global variables
  199. 						( "{0}`t{1}`t{2}" -f $_.Columns.Item( 1 ).Text, $Manufacturer, $Model ) | Out-String
  200. 					}
  201. 				}
  202. 			}
  203. 			[void] $workbook.Close( )
  204. 			[void] $objExcel.Quit( )
  205. 			if ( $Debug ) {
  206. 				Write-Host ( "Finished at {0} (elapsed time {1}" -f ( Get-Date ), $StopWatch.Elapsed )
  207. 				$StopWatch.Stop( )
  208. 			}
  209. 		}
  210. 	} else {
  211. 		if ( $Debug ) {
  212. 			Write-Host ( "Database folder `"{0}`" not found" -f $dbfolder )
  213. 		}
  214. 		if ( $Quiet ) {
  215. 			Exit 1
  216. 		} else {
  217. 			$message = "No downloaded Dutch aircraft registration database was found.`n`nDo you want to open the download webpage for the database now?"
  218. 			$title   = "No Database Found"
  219. 			$buttons = "YesNo"
  220. 			Add-Type -AssemblyName 'System.Windows.Forms'
  221. 			$answer = [System.Windows.Forms.MessageBox]::Show( $message, $title, $buttons )
  222. 			if ( $answer -eq 'Yes' ) {
  223. 				$url = 'https://www.ilent.nl/onderwerpen/luchtvaartuigregister/'
  224. 				Start-Process $url
  225. 			} else {
  226. 				ShowHelp( "No downloaded Dutch aircraft registration database found, please download it and try again" )
  227. 			}
  228. 		}
  229. 	}
  230. }
  231.  
  232. # Terminate Excel if requested and if this script's Excel process was the only instance
  233. $processcount = ( Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Measure-Object ).Count
  234. if ( $Debug ) {
  235. 	Write-Host ( "{0} active Excel processes when done" -f $processcount )
  236. }
  237. if ( $TerminateExcel -and !$excelactive -and ( $processcount -eq 1 ) ) {
  238. 	if ( $Debug ) {
  239. 		Write-Host "Terminating Excel now"
  240. 	}
  241. 	Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Stop-Process -ErrorAction 'SilentlyContinue'
  242. }
  243.  

page last modified: 2024-04-16; loaded in 0.0134 seconds