PowerShell -replace功能

时间:2017-12-14 17:22:17

标签: powershell replace

我正在尝试查找并替换文件中的字符串,然后将其保存到PowerShell中的原始文件中。

我已经尝试过了

(Get-Content "C:\Users\anon\Desktop\test.txt") 
-replace 'apple', 'apple1'
-replace 'bear' , 'bear1' |
Out-File test1.txt
pause

然而,我一直在

-replace : The term '-replace' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At C:\Users\Xing Chen\Desktop\test.ps1:2 char:1
+ -replace 'apple', 'apple1'
+ ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (-replace:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

我已经能够使用"abcd".replace()了,并且根据文档-replace也可以使用。

1 个答案:

答案 0 :(得分:1)

代码中没有任何内容表示行继续,并且解释器没有将-replace运算符视为同一命令的一部分。您有两种方法可以解决此问题:转义换行符或将命令放在同一行上。

@(Get-Content "C:\Users\anon\Desktop\test.txt") -replace 'apple','apple1' -replace 'bear','bear1' |
    Out-File -FilePath test1.txt
Pause

OR

@(Get-Content "C:\Users\anon\Desktop\test.txt") `
-replace 'apple','apple1' `
-replace 'bear','bear1' |
    Out-File -FilePath test1.txt
Pause