Nested Permissions Problem

I have this piece of code where I am trying to replace some lines in all files in a directory. I thought I could nest a foreach in a ForEach object, but this does not seem to work.

The error I get is:

InvalidArgument: (:) [ForEach-Object], ParameterBindingException


$files = Get-ChildItem $testdir\reference *.* -recurse
$replacementMap = @{"Fruit::Apple" = "NewApple";"Fruit::Banana" = "NewBanana"}

foreach ($file in $files)
    {
    If (Get-Content $($file.FullName) | Select-String -Pattern "Fruit::")
        {
        $content = Get-Content $($file.FullName) | ForEach-Object
               { 
               $line = $_
               foreach ($entry in $replacementMap.GetEnumerator())
                   {
                   $line -replace $($entry.Name),$($entry.Value)
                   }
                }
        $content = $content -join "`r`n"
        $content | Set-Content $($file.FullName)
     }

This code worked without

foreach ($entry in $replacementMap.GetEnumerator())
    {
    $line -replace $($entry.Name),$($entry.Value)
    }

part. Does anyone know what I'm doing wrong? thanks in advance

+4
source share
2 answers

You missed the close of the curly brace and the formatting problem on the foreach object. You have to take care of the foreach and foreach object differently:

Replace the existing foreach part as follows:

foreach ($file in $files)
{
    If(Get-Content $($file.FullName) | Select-String -Pattern "Fruit::")
    {
        $content = Get-Content $($file.FullName) | %{ 
                   $line = $_
                   foreach ($entry in $replacementMap.GetEnumerator())
                   {
                    $line -replace $($entry.Name),$($entry.Value)
                   }
        }
        $content = $content -join "`r`n"
        $content | Set-Content $($file.FullName)
    }
}
+2
source

, . , .

$replacementMap = @{
    "Fruit::Apple" = "NewApple"
    "Fruit::Banana" = "NewBanana"
}

Get-ChildItem $testdir\reference -File -Recurse | foreach {
    $content = Get-Content $_
    $dirty = $false
    foreach ($key in $replacementMap.Keys) {
        $content = $content -replace $key,$replacementMap.$key
        $dirty = $true
    }
    if ($dirty) { $content | Set-Content $_ }
}
+1

Source: https://habr.com/ru/post/1685511/


All Articles