1

I have the following script which reads in a file line by line and replaces a pattern in each line with specified text, then writes this to another file:

param
(
    [string] $inFilePath,
    [string] $outFilePath,
    [string] $inputPattern,
    [string] $replacePattern
)

function Main()
{
    $sr = $null;
    $sw = $null;

    try
    {
        $sr = New-Object System.IO.StreamReader($inFilePath);
        $sw = New-Object System.IO.StreamWriter($outFilePath, $true);
        do
        {
            $fileLine = $sr.ReadLine();
            $fileLine2 = "";
            if ($fileLine -eq $null)
            {
                break;
            }
            $fileLine = $fileLine + [System.Environment]::NewLine;
            $fileLine2 = [System.Text.RegularExpressions.Regex]::Replace($fileLine, $inputPattern, $replacePattern);
            $sw.Write($fileLine2);
        }
        while ($fileLine -ne $null);
    }
    finally
    {
        $sr.Dispose();
        $sw.Dispose();
    }
}

Main;

Unfortunately, when I save the script as filereplace.ps1 and call it like this:

powershell .\filereplace.ps1 c:\docs\infile.txt c:\docs\outfile.txt '.{30,}\->.*\r\n' '*'

I get this error:

The filename, directory name, or volume label syntax is incorrect.

Any idea what I might be doing wrong? I suspect there is something wrong with the regex pattern used in searching for a replacement - when I remove the \->, it works, but there is no reason why this should be a problem.

0

1 Answer 1

2

It is the redirection operator > that causes the problem in the command line. Enclose the whole command with ":

powershell ".\filereplace.ps1 c:\docs\infile.txt c:\docs\outfile.txt '.{30,}\->.*\r\n' '*'"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.