MadBoy MadBoy - 4 months ago 16
Powershell Question

Parse string in PowerShell to create output using variables

I want to create little script that takes particular type of string and uses it in a way I can process things easily


  • %1g.%s which basically means 1 char from given name and full secondary name (output should be j.snow built from 2 parameters)

  • %g.%s which basically means full given name dot and full secondary name (output should be john.snow built from 2 parameters)

  • %5g.%s which basically means 5 chars from given name and full secondary name but if given name is shorter use shorter version (john.snow)

  • %g%s which would given givenname and secondary name without dot (johnsnow)

  • etc



Question is how do I even start processing it so that I don't create a monster if/else cases? Or should I exactly do that?

EDIT. Since this is Microsoft Exchange Email Template behaviour just wanted to explain this is for Office 365 without on-premise option which doesn't have Email Templates option. In other words I want to create a script that would mimic this behaviour in some way.

Answer
$firstName = "Alice"
$lastName = "Bloggs"

$template = '%2g.%s@example.com'

function Get-NameSection {
    # Returns the first $num characters of a name
    # unless $num is 0, missing or longer than the name
    # then returns the entire name

    param([string]$name, [int]$num)

    if (-not $num -or $num -gt $name.Length) { 
        $name 
    } else {
        $name.Substring(0, $num)
    }
}

$template = [regex]::Replace($template, '%(\d*)g', {param($m) Get-NameSection $firstName $m.Groups[1].Value })
$template = [regex]::Replace($template, '%(\d*)s', {param($m) Get-NameSection $lastName $m.Groups[1].Value })

$template