(view source code of airregphcmd.ps as plain text)
<#
.SYNOPSIS
Search a downloaded Dutch aircraft registration database for a Dutch aircraft registation and if found, return the aircraft manufacturer and model (tab-delimited)
.DESCRIPTION
First, create a subdirectory 'PH' in this script's parent folder.
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.
Now run this script with an aircraft registration as its only parameter (see examples section).
The script will first look for the most recent Excel file in the 'PH' folder.
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.
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>).
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.
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.
Get-Help './AirRegPHCmd.ps1' -Examples will show 2 examples of this script being called by another script.
.PARAMETER Registration
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)
.PARAMETER TerminateExcel
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.
.PARAMETER Quiet
Ignore all errors and do not display any error messages; in case of errors, just terminate with return code 1.
.PARAMETER Debug
Show some progress messages
.PARAMETER Help
Show the script's help screen
.OUTPUTS
A tab-delimited string <registration><tab><manufacturer><tab><model> and manufacturer and model are also stored in output variables $Manufacturer and $Model.
.EXAMPLE
. ./AirRegPHCmd.ps1 "PH-PBB"
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"
.EXAMPLE
"PH-PBB" | . ./AirRegPHCmd.ps1
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"
.EXAMPLE
Create and run the following PowerShell script:
===============================================================
$Registration = 'PH-1AE' ; $Manufacturer = '' ; $Model = ''
[void] ( . "$PSScriptRoot\AirRegPHCmd.ps1" -Registration $Registration )
Write-Host ( "Registration : {0}`nManufacturer : {1}`nModel : {2}" -f $Registration, $Manufacturer, $Model )
===============================================================
Besides setting variables $Manufacturer to "HiSystems GmbH" and $Model to "MK OktoKopter XL2", it will return:
Registration : PH-1AE
Manufacturer : HiSystems GmbH
Model : MK OktoKopter XL2
.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 . ./AirRegPHCmd.ps1 PH-PBA') DO (
ECHO Registration : %%A
ECHO Manufacturer : %%B
ECHO Model : %%C
)
===============================================================
It will return:
Registration : PH-PBA
Manufacturer : Douglas Aircraft Company
Model : DC-3C-S1C3G
.LINK
Script written by Rob van der Woude:
https://www.robvanderwoude.com/
.LINK
Downloadable Dutch aircraft registration database in Excel format:
https://www.ilent.nl/onderwerpen/luchtvaartuigregister/
.LINK
Article "PowerShell - Read an Excel file using COM Interface" by François-Xavier Cat:
https://lazywinadmin.com/2014/03/powershell-read-excel-file-using-com.html
#>
param (
[parameter( ValueFromPipeline )]
[ValidatePattern("(^\s*$|[\?/]|^PH-[0-9A-Z]{3}$|^PH-[0-9]{2,4}$)")]
[string]$Registration,
[switch]$TerminateExcel,
[switch]$Quiet,
[switch]$Help
)
$progver = "1.03"
$Registration = $Registration.ToUpper( )
$Manufacturer = ''
$Model = ''
$ExcelError = $false
[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
}
# Check if Excel is already running
$excelactive = [bool]( ( Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Measure-Object ).Count -gt 0 )
if ( $Debug ) {
if ( $excelactive ) {
Write-Host "Excel already active at start"
} else {
Write-Host "Excel not active at start"
}
}
$dbfolder = ( Join-Path -Path $PSScriptRoot -ChildPath 'PH' )
if ( Test-Path $dbfolder ) {
$excelfile = ( Get-ChildItem -Path $dbfolder -Filter '* Aircraft registrations.xlsx' | Sort-Object $_.Name | Select-Object -Last 1 )
if ( $excelfile ) {
if ( $Debug ) {
Write-Host ( "Using Excel file `"{0}`"" -f $excelfile.FullName )
[System.Diagnostics.Stopwatch]::StartNew( )
Write-Host ( "Start searching for {0} in Excel file at {1}" -f $Registration, ( Get-Date ) )
}
$found = $false # will be set to True when a matching aircraft is found in the database
$ErrorActionPreference = 'SilentlyContinue' # Temporarily hide all error messages, we will handle the next one ourselves
# Open an Excel COM object
$objExcel = New-Object -ComObject Excel.Application -ErrorAction 'SilentlyContinue' -ErrorVariable ExcelError
$ErrorActionPreference = 'Continue' # Reenable output of future error messages
if ( $ExcelError ) {
ShowHelp( "Microsoft Excel not found" ) # Actually we were unable to open Excel's COM object
} else {
$ErrorActionPreference = 'SilentlyContinue' # Temporarily hide all error messages, we will handle the next one ourselves
# Open the Excel aircraft database file
$workbook = $objExcel.Workbooks.Open( $excelfile.FullName )
$ErrorActionPreference = 'Continue' # Reenable output of future error messages
# Check if the Excel file was successfully opened
if ( ![bool]( $objExcel.WorkBooks | Select-Object -Property Name ) ) {
$ErrorActionPreference = 'SilentlyContinue' # Ignore possible error when trying to close the Excel file and program
[void] $workbook.Close( )
[void] $objExcel.Quit( )
$ErrorActionPreference = 'Continue' # Reenable output of future error messages
ShowHelp( "Unable to open Excel file `"{0}`"" -f $excelfile.FullName )
}
# Iterate through all rows in the first sheet of the Excel file
$workbook.Sheets.Item( 1 ).UsedRange.Rows | ForEach-Object {
# After the first match we don't need to check for other matches, hence the check of the $found variable
if ( !$found ) {
if ( $_.Columns.Item( 1 ).Text -eq $Registration ) {
# We have a match!
if ( $Debug ) {
Write-Host ( "Found a match at {0}" -f ( Get-Date ) )
}
$found = $true # used instead of Break, which would also stop parent process; only slightly slower than Break
$Manufacturer = $_.Columns.Item( 6 ).Text # Manufacturer is in column 6
$Model = $_.Columns.Item( 8 ).Text # Model is in column 8
# By not using Write-Host, we allow calling scripts to suppress screen output and use passed on global variables
( "{0}`t{1}`t{2}" -f $_.Columns.Item( 1 ).Text, $Manufacturer, $Model ) | Out-String
}
}
}
[void] $workbook.Close( )
[void] $objExcel.Quit( )
if ( $Debug ) {
Write-Host ( "Finished at {0} (elapsed time {1}" -f ( Get-Date ), $StopWatch.Elapsed )
$StopWatch.Stop( )
}
}
} else {
if ( $Debug ) {
Write-Host ( "Database folder `"{0}`" not found" -f $dbfolder )
}
if ( $Quiet ) {
Exit 1
} else {
$message = "No downloaded Dutch aircraft registration 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://www.ilent.nl/onderwerpen/luchtvaartuigregister/'
Start-Process $url
} else {
ShowHelp( "No downloaded Dutch aircraft registration database found, please download it and try again" )
}
}
}
}
# Terminate Excel if requested and if this script's Excel process was the only instance
$processcount = ( Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Measure-Object ).Count
if ( $Debug ) {
Write-Host ( "{0} active Excel processes when done" -f $processcount )
}
if ( $TerminateExcel -and !$excelactive -and ( $processcount -eq 1 ) ) {
if ( $Debug ) {
Write-Host "Terminating Excel now"
}
Get-Process -Name "Excel" -ErrorAction 'SilentlyContinue' | Stop-Process -ErrorAction 'SilentlyContinue'
}
page last modified: 2024-04-16; loaded in 0.0385 seconds