Warm tip: This article is reproduced from stackoverflow.com, please click
powershell replace

Why is this powershell .Replace() not working?

发布于 2020-03-27 10:28:51

Any help to let me know what I am doing wrong here would be appreciated.

Here is the equivalent of what I am doing. I want the end result in $name to be just the persons name "Todd Welch" in this example but instead it is ending up as "A device that belongs to Todd Welch" so the replace is not working.

$name = "A device that belongs to Todd Welch"
$name = $user.Replace(".*device that belongs to ","")
$name = $name.Trim()
Write-host $name

Write host outputs "A device that belongs to Todd Welch"

Questioner
Todd Welch
Viewed
97
AdminOfThings 2019-07-03 23:56

.Replace() is from the string class and it does literal text replacements. Since you are using a regex mechanism .*, you need to switch to the -replace operator: The replacement text is unnecessary if you are just removing the text.

$data = "A device that belongs to Todd Welch"
$name = $data -replace ".*device that belongs to "
$name = $name.Trim()
$name