How do I insert text after a specific line in files using powershell?
As part of a huge refactoring I removed some duplicate classes and enums. I moved namespaces and restructured everything to be easier to maintain in the future.
All changes has been scripted already except for one thing. I need to insert a data contract namespace in every file that uses another namespace if the data contract namespace has not been inserted yet.
The code I have at the moment does not work but is sort of what I need I guess.
function Insert-Usings{
trap {
Write-Host ("ERROR: " + $_) -ForegroundColor Red
return $false
}
(Get-ChildItem $base_dir -Include *.asmx,*.ascx,*.cs,*.aspx -Force -Recurse -ErrorAction:SilentlyContinue) | % {
$fileName = $_.FullName
(Get-Content $fileName) |
Foreach-Object
{
$_
if ($_ -cmatch "using Company.Shared;") {
$_ -creplace "using Company.Shared;", "using Company.Common;"
}
开发者_运维问答 elseif ($_ -cmatch "using Company") {
#Add Lines after the selected pattern
"using Company.Services.Contracts;"
}
else{
$_
}
}
} | Set-Content $fileName
}
Edit: The code tends to output (overwrite the whole file with-) "using Company.Services.Contracts" statements.
It is not quite clear what you what to get exactly but I'll try to guess, see my comments in the code. The original code, I think, contains a few mistakes, one is serious: Set-Content
is used in a wrong pipeline/loop. Here is the corrected code.
function Insert-Usings
{
trap {
Write-Host ("ERROR: " + $_) -ForegroundColor Red
return $false
}
(Get-ChildItem $base_dir -Include *.asmx,*.ascx,*.cs,*.aspx -Force -Recurse -ErrorAction:SilentlyContinue) | % {
$fileName = $_.FullName
(Get-Content $fileName) | % {
if ($_ -cmatch "using Company\.Shared;") {
# just replace
$_ -creplace "using Company\.Shared;", "using Company.Common;"
}
elseif ($_ -cmatch "using Company") {
# write the original line
$_
# and add this after
"using Company.Services.Contracts;"
}
else{
# write the original line
$_
}
} |
Set-Content $fileName
}
}
For example, it replaces this:
xxx
using Company.Shared;
using Company;
ttt
with this:
xxx
using Company.Common;
using Company;
using Company.Services.Contracts;
ttt
Note: presumably you should not apply this code to sources more than once, the code is not designed for this.
精彩评论