Powershell:使用ForEach-Object [重复]的替换顺序

问题描述 投票:0回答:1

我正在Powershell中查找/替换单词。我对更换的顺序感到好奇。

想要用Test2顺序替换Test1,然后用Test3替换Test2的某些字符串组合(见下文)。

1)只是好奇下面是否可以安全编写代码?或Powershell是否同时运行事物,从而破坏了我的Required Sequence替换模式?

这似乎是行之有效的,只是想得到100%的肯定。否则,在第一次替换完成后,我可以编写另一个foreach循环。

2)另外,我是否需要下面的管道定界符?不知道他们做什么,从以前的程序员那里继承了这个脚本,尝试搜索和研究Powershell。

#Replace words in file
$TestFiles = Get-ChildItem $DBContextDestination   *.cs -rec
foreach ($file in $TestFiles )
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "abcd", "1234" } |
    Foreach-Object { $_ -replace "Test1;", "Test2" } |
    Foreach-Object { $_ -replace "Class Test2 Object", "Class Test3 Object" } |
    Set-Content -Encoding UTF8  $file.PSPath
}
powershell powershell-4.0 powershell-ise
1个回答
0
投票

是的,与Unix中的管道不同,后台没有运行。如果发送了一个对象,则它通过管道从左到右依次移动。您还可以链接替换项:

(Get-Content $file.PSPath) -replace "abcd", "1234" -replace "Test1;", 
  "Test2" -replace "Class Test2 Object", "Class Test3 Object"
© www.soinside.com 2019 - 2024. All rights reserved.