Last active
February 16, 2021 00:27
-
-
Save thedavecarroll/ccece8563e9fe995ef8c760c2d3c6abe to your computer and use it in GitHub Desktop.
Another PowerShell Math Challenge - IronScripter Challenge - 2021-02-09 (Intermediate Only)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#requires -Version 7 | |
function Get-SumTotal { | |
[CmdLetBinding()] | |
param( | |
[Parameter(Mandatory,Position = 0,ValueFromPipeline)] | |
[ValidatePattern('^\d{1,10}$', ErrorMessage = '"{0}" does not match only numbers 0-9 with a maximum of 10.')] | |
#[ValidatePattern('^\d{1,10}$')] | |
#[ValidateScript({ if ($_ -notmatch '^\d{1,10}$') { throw ('{0}"{1}" does not match only numbers 0-9 with a maximum of 10.' -f [System.Environment]::NewLine,$_) } else { $true }})] | |
[string]$Value, | |
[switch]$Full | |
) | |
process { | |
$NumberList = [System.Collections.ArrayList]::new() | |
$Value.ToCharArray() | ForEach-Object { | |
[void]$NumberList.Add([System.Char]::GetNumericValue($_)) | |
} | |
$SumTotal = $NumberList | Measure-Object -Sum | |
$Calculation = '{0} = {1}' -f ($NumberList -join ' + '),$SumTotal.Sum | |
$SumTotalOutput = [PsCustomObject]@{ | |
Value = $Value | |
NumberCount = $SumTotal.Count | |
Sum = $SumTotal.Sum | |
Calculation = $Calculation | |
} | |
$Calculation | Write-Verbose | |
if ($PSBoundParameters.ContainsKey('Full')) { | |
$SumTotalOutput | |
} else { | |
$SumTotalOutput.Sum | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are 2
Validate*
attributes that have been commented out.The
ValidatePattern
attribute, prior to PowerShell Core, displays a generic, hard-to-read error message. The commented out attribute shows how to validate in Windows PowerShell 5.1. The other, uncommented, shows how to validate with PowerShell Core (6.x) and PowerShell (7.x).The commented
ValidateScript
shows one way to provide the user with a more specific error message. This requires more code than the targeted validate attributes and can support more complex validation rules. I could have easily stayed with this attribute, but I chose to go with PowerShell 7 hence the#Requires
statement.