Felix ccad
Felix ccad

Reputation: 97

Powershell + in a string not valid

I have to replace a phone number in a document but when there is no phone number from mu user I have to delete this row The default document looks like this:

company
street
T: +00 xxx xxx xxx  #phone
F: +00 xxx xxx xxx  #Fax
M: +00 xxx xxx xxx  #Mobile

When for example a user has no mobile phone I have to delete this row

$content = $content -replace "M:",""
$content = $content -replace "+00",""
$content = $content -replace "xxx xxx xxx",""

But I'm getting this error

The regular expression pattern +39 is not valid.
At line:65 char:1
+ $content = $content -replace "+39",""
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (+39:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

How can I now delete this row when power shell doesn't want my + in a string

Delete the row:

After deleting successful the mobile number document looks like this:

company
street
T: +00 xxx xxx xxx  #phone
F: +00 xxx xxx xxx  #Fax

more information

But it should look like this

company
    street
    T: +00 xxx xxx xxx  #phone
    F: +00 xxx xxx xxx  #Fax
    more information

Upvotes: 1

Views: 272

Answers (2)

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

Don't use regex replace, but use String.Replace:

$content = $content.Replace("M:","")
$content = $content.Replace("+00","")
$content = $content.Replace("xxx xxx xxx","")

This should work for you:

$content = Get-Content $filepath | foreach-object { if (!$_.StartsWith("M:")) { $_ } }
$content

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 58931

You could also use a regex to filter them:

$content | Where { $_ -notmatch '^M: \+00' }

Upvotes: 1

Related Questions