0

my code replace one text for another text well

$pathhh = "E:\times"
$searchWords = 'NEWYORK'
$replaceWord = 'CANCELED'

Foreach ($sw in $searchWords)
{
    Get-Childitem -Path $pathhh -Recurse | 
    Select-String -Pattern "$sw" | 
    Select Path,LineNumber,@{n='SearchWord';e={$sw}}
}

if (1 -eq 1) {
$files = Get-Childitem -Path $pathhh -File -Recurse
foreach ($file in $files) {
  $content = get-content -raw $file.PSPath
  # regex may have problems
  $content = $content -replace $searchWords,
    $replaceWord
  set-content $file.PSPath $content
}

}

but I need more different replacements like

replace NEWYORK with CANCELLED and replace LA with INFO and replace LONDON with DELAYED so more text replacements so like

$searchWords = 'NEWYORK,LA,LONDON'
$replaceWord = 'CANCELED,INFO,DELAYED'

but have no idea how to connect it all together thank you for your help!

1
  • 1
    take a look at hashtables - Get-Help about_Hash_Tables. they are REALLY good for lookup tables since they consist of a unique key and a value. [grin] Commented Jun 29, 2020 at 9:15

1 Answer 1

3

Instead of using two comma delimited strings as you are trying now, I would suggest creating a replacements map (Hashtable) to store the words to replace and their replacement strings in one easy to use structure.

Something like this:

$replacements = @{
    'NEWYORK' = 'CANCELLED'
    'LA'      = 'INFO'
    'LONDON'  = 'DELAYED'
}

$files = Get-Childitem -Path $pathhh -File -Recurse
foreach($file in $files) {
    $content = Get-Content -Path $file.FullName -Raw
    foreach ($item in $replacements.Keys) {
        $content = $content.Replace($item, $replacements[$item])
    }
    Set-Content -Path $file.FullName -Value $content
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh man thank you SO MUCH! was thinking after asking my question that better way would be to have a replacement list on more lines so every replacement is new line because there will be a lot of replacements and it will be way more friendly to read.. and then seeing your answer that it already contains that feature = thank you so much! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.