PowerShell for verifying Norwegian social security number / personnummer

function Get-IsSSNValid
{
    [CmdletBinding()]
    [Alias()]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   Position=0)]
        [String] $SSN
    )
 
  
 
    Process
    {
        $FirstPart = $SSN.Substring(0,9)
        $Check = $SSN.Substring(9,2)
 
  
 
        $k1 = 11 - ((3 * [int]::Parse($FirstPart.Chars(0)) + 7 * [int]::Parse($FirstPart.Chars(1)) + 6 * [int]::Parse($FirstPart.Chars(2)) + 1 * [int]::Parse($FirstPart.Chars(3)) + 8 * [int]::Parse($FirstPart.Chars(4)) + 9 * [int]::Parse($FirstPart.Chars(5)) + 4 * [int]::Parse($FirstPart.Chars(6)) + 5 * [int]::Parse($FirstPart.Chars(7)) + 2 * [int]::Parse($FirstPart.Chars(8))) % 11)
        if($k1 -eq "11") {
            $k1 = 0
        }

        $k2 = 11 - ((5 * [int]::Parse($FirstPart.Chars(0)) + 4 * [int]::Parse($FirstPart.Chars(1)) + 3 * [int]::Parse($FirstPart.Chars(2)) + 2 * [int]::Parse($FirstPart.Chars(3)) + 7 * [int]::Parse($FirstPart.Chars(4)) + 6 * [int]::Parse($FirstPart.Chars(5)) + 5 * [int]::Parse($FirstPart.Chars(6)) + 4 * [int]::Parse($FirstPart.Chars(7)) + 3 * [int]::Parse($FirstPart.Chars(8)) + 2 * $k1) % 11)
        if($k2 -eq "11") {
            $k2 = 0
        }
        return [int]::Parse($Check.Chars(0)) -eq $k1 -and [int]::Parse($Check.Chars(1)) -eq $k2
    }
}
 
  
 
Get-IsSSNValid "12345678910"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s