2013-05-01 105 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