2013-05-01 106 views
0

在我的PowerShell脚本中,我收到了一个我不明白的错误。字符串替换PowerShell中的错误

的错误是:

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 "usermenuTest2.4d.new" 
    + CategoryInfo   : InvalidOperation: (
Menu "User" {...do" 
    } 
} 
:String) [], RuntimeException 
    + FullyQualifiedErrorId : InvalidRegularExpression 

我的脚本文件读入一个字符串(字符串A)然后尝试从另一个文件中删除String一个。这个错误意味着什么,我该如何修复它?

我的代码:

#set-executionpolicy Unrestricted -Force 
#set-executionpolicy -scope LocalMachine -executionPolicy Unrestricted -force 

$target=[IO.File]::ReadAllText(".\usermenuTest1.4d") 
$output=[IO.File]::ReadAllText(".\usermenuTest2.4d") 

($output -replace $target) | Set-Content "usermenuTest2.4d.new" 

回答

2

尝试:

($output -replace [regex]::escape($target)) 
-replace $target

总是被评估为regular expression。 在你的情况下,$target包含一些regex special character,无法正确解析,那么你需要转义所有特殊字符。 [regex]::escape() .net方法有助于完成这项工作。

0

这可能是因为$ target为空(所以是$ output)。

.NET用初始工作目录(通常是您的主目录或systemroot)启动PowerShell的工作目录代替点。我猜usermenuTest1.4d位于不同的目录中,并且您正在从该目录运行此脚本。 ReadAllText正在寻找初始目录中的文件,但没有找到它。

如果你在其中usermenuTest1.4d所在目录的命令提示符下运行$target=[IO.File]::ReadAllText(".\usermenuTest1.4d"),你会看到一个错误,告诉你它找不到该文件,并显示您的完整路径,它正在因为这将与你的预期不同。或者,你可以在下面的行添加到您的脚本,看哪个目录将取代与点:

[environment]::currentdirectory 

下列任何一项应该工作:

$target = Get-Content .\usermenuTest1.4d | Out-String

$target = [IO.File]::ReadAllText("$pwd\usermenuTest1.4d")

$target = [IO.File]::ReadAllText((Resolve-Path usermenuTest1.4d))

[environment]::currentdirectory = $pwd 
$target=[IO.File]::ReadAllText('.\usermenuTest1.4d') 

最后一个是不必要的繁琐,但我用它来帮助明确发生了什么。

当然,您应该在设置$输出时也这样做。

+0

如果'$ target'或'$ output'是'$ null'否'InvalidRegularExpression' 异常将会是trhow。不是这个错误。 – 2013-05-03 11:07:39