Skip to content

Instantly share code, notes, and snippets.

@inammathe
Last active August 28, 2018 22:28
Show Gist options
  • Save inammathe/7b1903efd8102b61a0306f7405e2c22f to your computer and use it in GitHub Desktop.
Save inammathe/7b1903efd8102b61a0306f7405e2c22f to your computer and use it in GitHub Desktop.
Test-CCNumber - Uses the Luhn algorithm to test if a number is a valid credit card number or not
Function Test-CCNumber {
<#
.SYNOPSIS
Tests for valid credit card numbers
.DESCRIPTION
Uses the Luhn algorithm to test if a number is a valid credit card number or not
.EXAMPLE
PS C:\> Test-CCNumber -Number 9003085869539691
Tests the number 9003085869539691
.EXAMPLE
PS C:\> 4916910011471997, 2720996758722767, 342993248239546 | Test-CCNumber
Tests the numbers 4916910011471997, 2720996758722767, 342993248239546
.NOTES
Based off method described here: https://planetcalc.com/2464/
See https://en.wikipedia.org/wiki/Luhn_algorithm for more information
#>
param
(
# Numbers to test for valid Luhn
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[long[]]
$Number
)
Begin {
function Test-Luhn($Number) {
# Convert to Array
$array = [int[]](($Number -split '') -ne '')
# From the rightmost digit, which is the check digit, and moving left, double the value of every second digit. The check digit is not doubled; the first digit doubled is immediately to the left of the check digit. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then subtract 9 from the product (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).
for ($i = $array.Count - 1; $i -ge 0; $i--) {
if (($i -ne $array.Count - 1) -and $i % 2 -eq 0) {
$array[$i] = $array[$i] * 2
if ($array[$i] -gt 9) {
$array[$i] = $array[$i] - 9
}
}
}
# Take the sum of all the digits.
$sum = $array | Measure-Object -Sum | Select-Object -ExpandProperty Sum
# If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
Write-Output (($sum) % 10 -eq 0)
}
}
Process
{
foreach ($n in $Number) {
[PSCustomObject]@{
Number = $n
Valid = Test-Luhn $n
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment