String Replace Error in PowerShell

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 6 years, 2 months ago.

  • Author
  • #5872

    by gretty at 2013-04-30 22:36:35


    In my PowerShell script I am getting an error that I dont understand.

    The error is:
    [quote] Windows PowerShell
    Copyright (C) 2009 Microsoft Corporation. All rights reserved.

    Invalid regular expression pattern:
    Menu "User" {
    Button "EXDS" {
    Walk_Right "EXDS"
    At C:\test.ps1:7 char:18
    + ($output -replace < <<< $target) | Set-Content ""
    + CategoryInfo : InvalidOperation: (
    Menu "User" {"
    :String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression[/quote]

    My script reads a file into a string (string A) then attempts to remove String A from another file. What does this error mean and how I can I fix it?

    My code:
    #set-executionpolicy Unrestricted -Force
    #set-executionpolicy -scope LocalMachine -executionPolicy Unrestricted -force


    ($output -replace $target) | Set-Content ""

    by mjolinor at 2013-05-01 03:24:48

    That's impossible to say exactly without knowing what's in $Target. Regular expressions have their own syntax rules and set of reserved characters.

    If you're wanting to match what's in $Target the regex metacharacters need to be escaped with backslashes in order to be interpreted literally. Fortunately the [regex] type has a static escape method you can use to do that for you:

    $TargetRegex = [Regex]]

    Then do your match opertation using $TargetRegex

    ($output -replace $TargetRegex) | Set-Content ""

You must be logged in to reply to this topic.