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

标签 powershell powershell-2.0

我有以下脚本:

$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 block 中:

$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    
}

关于powershell - 在 PowerShell 中为 -replace 和 Set-Content 组合文件 IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39111060/

相关文章:

powershell - 使用 powershell 将文本附加到文件

windows - 加载 PowerShell 历史记录

powershell - 如何从 powershell 模块函数导出变量?

powershell - 如何将 foreach 循环输出转储到 PowerShell 中的文件中?

powershell - 在 Powershell 中创建 Outlook 规则时出错

powershell - 使用 PowerShell 从包含字符串的文本文件中删除行

powershell - 保留PowerShell函数的返回类型

.net - 在.Net中,有没有办法让 [System.IO.File]::ReadAllLines($file) 读取部分锁定的文件?

powershell - 在计算属性上设置宽度对输出没有影响

powershell - 如何使用 powershell 的 read-host 功能接受外部服务的密码?