在 PowerShell 中为 -replace 和 Set-Content 组合文件 IO

Combine file IO for -replace and Set-Content in PowerShell

我有以下脚本:

$allFiles = Get-ChildItem "./" -Recurse | Where { ($_.Extension -eq ".ts")}
foreach($file in $allFiles)
{
    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) | 
        Foreach-Object {$_ -replace "my-project-name", '$appNameDashCased$'} |
        Set-Content $file.PSPath    

    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) | 
        Foreach-Object {$_ -replace "MyProjectName", '$appNameCamelCased$'} |
        Set-Content $file.PSPath    

    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) | 
        Foreach-Object {$_ -replace "myProjectName", '$appNamePascalCased$'} |
        Set-Content $file.PSPath    
}

它需要一个文件并进行一些替换,然后保存文件。然后它使用相同的文件并进行更多替换,然后再次保存文件。然后它再做一次。

这可行,但似乎效率低下。

有没有办法全部替换完然后保存一次文件?

(如果可能的话,我更愿意保持PowerShell的可读风格。)

当然,只需将您的替换链接到 ForEach-Object 块内:

$allFiles = Get-ChildItem "./" -Recurse | Where { ($_.Extension -eq ".ts")}
foreach($file in $allFiles)
{
    (Get-Content $file.PSPath) | 
        Foreach-Object {
            # Find and replace the dash cased the contents of the files
            $_ -replace "my-project-name", '$appNameDashCased$' `
               -replace "MyProjectName", '$appNameCamelCased$' `
               -replace "myProjectName", '$appNamePascalCased$'
        } |
        Set-Content $file.PSPath    
}

这是可以做到的,而且实际上比你现在做的要简单得多。您可以这样链接 -Replace 命令:

$allFiles = Get-ChildItem "./" -Recurse | Where { ($_.Extension -eq ".ts")}
foreach($file in $allFiles)
{
    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) -replace "my-project-name", '$appNameDashCased$' -replace "StringB", '$SecondReplacement$' -replace "StringC", '$ThirdReplacement$' | Set-Content $file.PSPath
}