Vaccano Vaccano - 3 months ago 20
PowerShell Question

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

I have the following script:

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


It takes a file and does some replacing, then saves the file. Then it takes the same file and does some more replacing then saves the file again. Then it does it one more time.

This works, but seems inefficient.

Is there a way to do all the replacing and then save the file once?

(If possible, I would prefer to keep the readable style of PowerShell.)

Answer

Sure, just chain your replaces inside the 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    
}
Comments