PowerShell Snippet: Trimming The String!
Hello!
When building up urls from different parameters in something like TeamCity, or Octopus, it’s simple enough to get double “//” in urls if the parameters are not consistent. So little helper functions are always useful to have imported to manage such things. Below is an example of such a thing!
function Update-Parameter
{
param
(
$param,
$character,
[bool] $trimstart = $false,
[bool] $trimend = $false
)
if ($trimstart)
{
$StringChecker = $param.StartsWith($character)
if ($StringChecker -eq "True")
{
$param = $param.TrimStart($character)
}
}
if ($trimend)
{
$StringChecker = $param.EndsWith($character)
if ($StringChecker -eq "True")
{
$param = $param.TrimEnd($character)
}
}
return $param
}
$url = "https://academy.microsoft.com/"
$lan = "/en-us/"
$ext = "/professional-program/data-science/"
$trim = "/"
$output = "Before Trim {0}/{1}/{2}" -f $url, $lan, $ext
$output
$url = Update-parameter $url $trim $false $true
$lan = Update-parameter $lan $trim $true $true
$ext = Update-Parameter $ext $trim $false $true
$output = "After Trim {0}/{1}/{2}" -f $url, $lan, $ext
$output