GreetRufus
GreetRufus

Reputation: 431

Powershell - using variables in replace

I was using .replace until I discovered it is case sensitive. So I am rewritng a line of code to use -replace instead.

Here is what is working, but is case sensitive:

$SourcePath = 'c:\scripts\test
$folder = 'c:\testing\test'
$sourceFullPath = 'c:\scripts\test\FolderToTest'
$sourceFileRelativePath = $sourceFullPath.Replace($SourcePath, "")
$destFullFilePath = $folder + $sourceFileRelativePath

Write-output $destFullFilePath
c:\testing\test\FolderToTest

How would I convert this to use -replace or is there a way to use the .net .replace case-insensitive?

Note: This section of code will be in a function so they will not be static. I put in examples for this post but they could be any file path.

Thanks!!

Upvotes: 0

Views: 544

Answers (1)

Shay Levy
Shay Levy

Reputation: 126732

Unlike the Replace method which takes strings, the replace operator takes a regular expression pattern. $SourcePath needs to be escaped as it contains backslashes which are special regex characters.

$sourceFileRelativePath  = $sourceFullPath -replace [regex]::escape($SourcePath)
$destFullFilePath = Join-Path $folder $sourceFileRelativePath

Upvotes: 1

Related Questions