-
Notifications
You must be signed in to change notification settings - Fork 60
/
Replace-Token.ps1
49 lines (40 loc) · 1.59 KB
/
Replace-Token.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function Replace-Token {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')]
[CmdletBinding()]
param(
[string] $String,
[object] $Source
)
[string] $result = $String
[regex] $tokenMatcher = '%{(?<token>\w+?)?(?::?\+(?<datefmtU>(?:%[ABCDGHIMRSTUVWXYZabcdeghjklmnprstuwxy].*?)+))?(?::?\+(?<datefmt>(?:.*?)+))?(?::(?<padding>-?\d+))?}'
$tokenMatches = @()
$tokenMatches += $tokenMatcher.Matches($String)
[array]::Reverse($tokenMatches)
foreach ($match in $tokenMatches) {
$formattedEntry = [string]::Empty
$tokenContent = [string]::Empty
$token = $match.Groups["token"].value
$datefmt = $match.Groups["datefmt"].value
$datefmtU = $match.Groups["datefmtU"].value
$padding = $match.Groups["padding"].value
[hashtable] $dateParam = @{ }
if (-not [string]::IsNullOrWhiteSpace($token)) {
$tokenContent = $Source.$token
$dateParam["Date"] = $tokenContent
}
if (-not [string]::IsNullOrWhiteSpace($datefmtU)) {
$formattedEntry = Get-Date @dateParam -UFormat $datefmtU
}
elseif (-not [string]::IsNullOrWhiteSpace($datefmt)) {
$formattedEntry = Get-Date @dateParam -Format $datefmt
}
else {
$formattedEntry = $tokenContent
}
if ($padding) {
$formattedEntry = "{0,$padding}" -f $formattedEntry
}
$result = $result.Substring(0, $match.Index) + $formattedEntry + $result.Substring($match.Index + $match.Length)
}
return $result
}