MykeDev
MykeDev

Reputation: 5

Replace first character in PowerShell

I have to replace the first character in a string. I have a snippet like this:

 if(!([string]::Compare($filestmp.Substring(0,1), "M", $True)))
 {
     echo cos
     $filestmp = $filestmp.Replace('^(.*?)M(.*)', 'Zmodyfikowany  ')
 }

The code doesn't throw any exceptions, and it doesn't work either. The if condition passes, since my echo statement is printed. What am I doing wrong here?

Upvotes: 0

Views: 2088

Answers (2)

Esperento57
Esperento57

Reputation: 17462

Other solution:

$filestmp = "M Log.txt"

# Test equal which ignores case
if ($filestmp.Substring(0,1) -ieq "M")
{
    $filestmp = "'Zmodyfikowany{0}" -f  $filestmp.Substring(1)
}

# Test like which ignores case
if ($filestmp -ilike "M*")
{
    $filestmp = "'Zmodyfikowany{0}" -f  $filestmp.Substring(1)
}

Upvotes: 0

Christopher G. Lewis
Christopher G. Lewis

Reputation: 4836

RegEx is overkill.

Use a simple substring:

$filestmp=("Zmodyfikowany" +  $filestmp.SubString(1) )

Upvotes: 4

Related Questions