Jan 20, 2014

Powershell - replace text in file(s) & custom functions in separate script

PowerShell example how to replace string and use custom function.
On bottom is example that uses regex expression for replace.

."c:\Users\sinisabencetic\Dropbox\*******\Dcs5Net\dcs5net-lib.ps1"
<# AdServer root folder
#>
$devRoot = "c:\Development\DCS5Net\trunk\WebSite\Config\";
$target = $devRoot + "AppSettings.config"
<# This is syntax for calling parameter less functions#>
DisableFVB
DisableGF
<# Enable FVB config #>
(Get-Content $target) | Foreach-Object {
$_ -replace '<appSettings>',
'<appSettings><add key="FVBPortal" value="True"/>'
} | Set-Content $target

dcs5net-lib.ps1

function DisableFVB
{
<# Disable FVB config #>
<#  If exists commented remove it
#>
(Get-Content $target) | Foreach-Object {
$_ -replace '<!--<add key="FVBPortal" value="True"/>-->',
   ''
} | Set-Content $target <#
If exists uncommented remove it
#>
(Get-Content $target) | Foreach-Object {
$_ -replace '<add key="FVBPortal" value="True"/>',
   ''
} | Set-Content $target
}


This code replaces attribute value contents. It expects chars or \ in match expression and replaces it with contents of variable provided as argument of function.

function FixAppSett($pathToReport)
{
$webconfig = "c:\Development\DCS5Net\trunk\WebSite\web.config"
(Get-Content $webconfig) | Foreach-Object { $_ -replace "(<add key=`"OrdnerBerichte`" value=`")([a-zA-Z\\]+)(`"/>)","`$1$pathToReport`$3"
} | Set-Content $webconfig
}

No comments:

Post a Comment