forked from ligershark/template-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-replacer.psm1
112 lines (92 loc) · 3.06 KB
/
file-replacer.psm1
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
[cmdletbinding()]
param(
[Parameter(Position=0)]
$pathToReplacerAssembly
)
Set-StrictMode -Version 3
function Get-ScriptDirectory{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$scriptDir = ((Get-ScriptDirectory) + "\")
$buildprops = new-object psobject -Property @{
ReplacerAssemblyFileName = 'LigerShark.FileReplacer.dll'
ReplacerAssemblyLoaded = $false
}
function FindReplacerAssembly{
[cmdletbinding()]
param()
process{
$foundPath = $null
$pathsToCheck = @()
if($env:ReplacerAssemblyFilePath){
$pathsToCheck += $env:ReplacerAssemblyFilePath
}
$pathsToCheck += (join-path $scriptDir $buildprops.ReplacerAssemblyFileName)
foreach($path in $pathsToCheck){
'Looking for replace assembly at [{0}]' -f $path | Write-Verbose
if(test-path $path){
'Found replacer assembly at [{0}]' -f $path | Write-Verbose
$foundPath = $path
break
}
}
$foundPath
}
}
function LoadReplacerAssembly{
[cmdletbinding()]
param(
[switch]$force
)
process{
if($force){
$buildprops.ReplacerAssemblyLoaded=$false
}
if(!($buildprops.ReplacerAssemblyLoaded)){
$pathtoreplacerAssembly = FindReplacerAssembly
if(!$pathtoreplacerAssembly){
throw ('Unable to find the replacer assembly')
}
'Loading replacer assembly from [{0}]' -f $pathtoreplacerAssembly | Write-Verbose
Add-Type -path $pathtoreplacerAssembly
}
else{
'LoadReplacerAssembly skipping the load for the assembly since it has already been loaded' | Write-Verbose
}
}
}
function Replace-TextInFolder{
[cmdletbinding()]
param(
[Parameter(Position=0)]
[ValidateScript({test-path $_})]
[string]$folder,
[Parameter(Position=1)]
[hashtable]$replacements,
[Parameter(Position=2)]
[ValidateNotNullOrEmpty()]
[string]$include='*.*',
[Parameter(Position=3)]
[string]$exclude
)
begin{ LoadReplacerAssembly }
process{
try{
$folder = (Get-Item $folder).FullName
'Starting replacements in folder [{0}]' -f $folder | Write-Verbose
# convert replacements to correct object
$repDictionary = New-Object 'system.collections.generic.dictionary[string,string]'
$replacements.Keys | % {
$repDictionary.Add($_,$replacements[$_])
}
$logger = new-object System.Text.StringBuilder
$replacer = new-object LigerShark.TemplateBuilder.Tasks.RobustReplacer
$replacer.ReplaceInFiles($folder,$include,$exclude,$repDictionary,$logger)
$logger.ToString() | Write-Verbose
}
catch{
throw("Unable to complete replacements.`nError: [{0}]" -f ($_.Exception.Message))
}
}
}