Powershell:用 ForEach-Object 替换的顺序
Powershell: Order of Replacement with ForEach-Object
我是 finding/replacing Powershell 中的单词。很好奇替换顺序
想要依次用Test2替换Test1,然后用Test3替换Test2的某些字符串组合(见下文)。
1)
只是好奇下面的代码是否安全?或者 Powershell 运行 同时进行,从而打破我的 Required Sequence 替换模式?
好像可以,只是想百分百确定。否则,我可以在第一次替换完成后编写另一个 foreach 循环。
2)
另外,我需要下面的竖线分隔符吗?不确定他们做了什么,从以前的程序员那里继承了这个脚本,试图 google 并研究 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
}
是的,与 unix 中的管道不同,没有任何东西在后台运行。如果发送一个对象,它会按顺序从左到右通过管道。您还可以链接替换。 Test1后面应该有分号吗?
(Get-Content $file.PSPath) -replace "abcd", "1234" -replace "Test1;",
"Test2" -replace "Class Test2 Object", "Class Test3 Object"
我是 finding/replacing Powershell 中的单词。很好奇替换顺序
想要依次用Test2替换Test1,然后用Test3替换Test2的某些字符串组合(见下文)。
1) 只是好奇下面的代码是否安全?或者 Powershell 运行 同时进行,从而打破我的 Required Sequence 替换模式?
好像可以,只是想百分百确定。否则,我可以在第一次替换完成后编写另一个 foreach 循环。
2) 另外,我需要下面的竖线分隔符吗?不确定他们做了什么,从以前的程序员那里继承了这个脚本,试图 google 并研究 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
}
是的,与 unix 中的管道不同,没有任何东西在后台运行。如果发送一个对象,它会按顺序从左到右通过管道。您还可以链接替换。 Test1后面应该有分号吗?
(Get-Content $file.PSPath) -replace "abcd", "1234" -replace "Test1;",
"Test2" -replace "Class Test2 Object", "Class Test3 Object"