-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReplaceTextIn-File.ps1
65 lines (49 loc) · 1.61 KB
/
ReplaceTextIn-File.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<#
.SYNOPSIS
Replace de strings em multiplos arquivos
.DESCRIPTION
Replace de strings em multiplos arquivos
.EXAMPLE
ReplaceTextIn-File.ps1 -Path e:\temp\arquivo*.xml -Find 'item' -Replace 'itens' -Overwrite -Recurse -Verbose
.INPUTS
Inputs (if any)
.OUTPUTS
Output (if any)
.NOTES
General notes
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)]
[ValidateScript( { Test-Path -Path $_ })]
[String] $Path,
# string a ser subtituida
[Parameter(Mandatory = $true)]
[String] $Find,
# string subtituta
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[String] $Replace,
# sobreescreve o arquivo de saida
[switch] $Overwrite,
# pesquisa recursiva
[Switch] $Recurse
)
# contador de ocorrencias do replace
$countNeedleFinded = 0;
Get-ChildItem -Path $Path -Recurse:$Recurse -File | ForEach-Object {
$count = (Select-String -Path $_.FullName -Pattern $Find -AllMatches).Matches.Count;
if ($VerbosePreference -eq "Continue")
{ "$($_.Name): $count ocorrência(s)"; }
if ($count -gt 0)
{
# replace case sensitive
(Get-Content -LiteralPath $_.FullName | ForEach-Object { $_ -creplace $Find, $Replace; }) | Set-Content -Path "$($_.FullName).temp";
$FileOut = $_.FullName + @{ $true = '.true'; $false = '.replaced' }[$Overwrite.IsPresent];
Move-Item -Path "$($_.FullName).temp" -Destination $FileOut -Force -ErrorAction Stop;
}
$countNeedleFinded += $count;
}
"-----------------";
"Total de $countNeedleFinded ocorrência(s)";