function Encode-String {
[CmdletBinding(ConfirmImpact='Low')]
Param(
[Parameter(Mandatory=$false)][String]$DTR = 'AZERTY123456789012345',
[Parameter(Mandatory=$false)][Int]$CountOfPrefixDigitsToKeep = 4,
[Parameter(Mandatory=$false)][Int]$CountOfSuffixDigitsToKeep = 4,
[Parameter(Mandatory=$false)][Char]$FillerCharacter = 'X'
)
Begin { }
Process {
# Identify Numerical/non numerical characters
$NonNumericalPart = ([Char[]]$DTR | foreach { if ([Int]$_ -le 47 -or [Int]$_ -ge 58) {$_} }) -join ''
$NumericalPart = ([Char[]]$DTR | foreach { if ([Int]$_ -ge 48 -and [Int]$_ -le 57) {$_} }) -join ''
Write-Verbose "Identified Non-numerical part as '$NonNumericalPart', and Numerical part '$NumericalPart'"
# Concatenate and output the desired string
$NonNumericalPart +
$NumericalPart.Substring(0,$CountOfPrefixDigitsToKeep) +
[String]$FillerCharacter*($NumericalPart.Length-($CountOfPrefixDigitsToKeep+$CountOfSuffixDigitsToKeep)) +
$NumericalPart.Substring(($NumericalPart.Length-$CountOfSuffixDigitsToKeep),$CountOfSuffixDigitsToKeep)
}
End { }
}
This will work for different size strings like those containing 15,16,17,18 digits:
Encode-String 'AZERTY1234567890123456' -Verbose # 16
VERBOSE: Identified Non-numerical part as 'AZERTY', and Numerical part '1234567890123456'
AZERTY1234XXXXXXXX3456
It can handle different count of digits in the beginning (Prefix) as in:
Encode-String -DTR 'AZERTY123456789012345' -CountOfPrefixDigitsToKeep 6 -Verbose
VERBOSE: Identified Non-numerical part as 'AZERTY', and Numerical part '123456789012345'
AZERTY123456XXXXX2345
or the end (Suffix) as in:
Encode-String -DTR 'AZERTY123456789012345' -CountOfSuffixDigitsToKeep 7 -Verbose
VERBOSE: Identified Non-numerical part as 'AZERTY', and Numerical part '123456789012345'
AZERTY1234XXXX9012345
Notice that this function does not care where the digits are located in the string. For example, ‘AZERTY123456789012345’ and ‘1A2Z3E4R5T6Y789012345’ will produce the same output:
Encode-String 'AZERTY123456789012345' -Verbose
VERBOSE: Identified Non-numerical part as 'AZERTY', and Numerical part '123456789012345'
AZERTY1234XXXXXXX2345
Encode-String '1A2Z3E4R5T6Y789012345' -Verbose
VERBOSE: Identified Non-numerical part as 'AZERTY', and Numerical part '123456789012345'
AZERTY1234XXXXXXX2345
Finally, this function does not do any error checking. In a production environment you may want to anticipate all manners of bad input, like
Encode-String -DTR 'AZERTY123456789012345' -CountOfPrefixDigitsToKeep 16 -Verbose
VERBOSE: Identified Non-numerical part as 'AZERTY', and Numerical part '123456789012345'
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At line:21 char:9
+ $NonNumericalPart +
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException