PowerShell Snippet #4

Hello!

 

Below is a function that will search in  a string and replace a character in a variable. Simple enough. It generally saves time in calling this from a helper file in source control for tidying up variables that are passed in to a Powershell function that aren’t quite formatted as required. A good example of this is upstream build variables with spaces in TeamCity.


Function FormatReplaceVariable
{
[CmdletBinding()]
param([parameter(Mandatory=$true)]
[string]$param,
[string]$find,
[string]$substitute)

Write-Host "Replacing characters $find with $substitute in $param" -Verbose
$param = $param -replace "$find", "$substitute"
Write-Host "Now parameter looks like $param" -Verbose
return $param
}

$bob = FormatReplaceVariable -param "as'lfjksaj'JASD;oasdjf'asd aasd asd; ghas'fkasdf;aksd" -find ";" -substitute "!!!!"
write-host $bob

Author: Richie Lee

Full time computer guy, part time runner. Full time Dad, part time blogger. Pokémon Nut. Writer of fractured sentences. Maker of the best damn macaroni cheese you've ever tasted.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s