Forum Discussion

Hjb118's avatar
Hjb118
Copper Contributor
Feb 04, 2023
Solved

Replace specific letters and word in a text file

Good Afternoon, I am trying to create script that will take file, read each line, replace a specific word/letter, then output that line to new file but having trouble replacing the words/letters. ...
  • AndySvints's avatar
    Feb 04, 2023

    Hello Hjb118,

    You can achieve needed result with one foreach loop:

    $filePath = ".\input.txt"
    $newFilePath = "output.txt"
    
    $configurationData = New-Object System.Collections.Generic.Dictionary"[String,String]"
    $configurationData.add("<Password>","blah")
    $configurationData.add("<A>","0")
    $configurationData.add("<x>","0")
    
    $replacementlist = @("<Password>","<A>","<x>")
    
    $InputData=Get-Content $filePath
    foreach($key in $replacementlist){
        $InputData=$InputData -replace $key,$configurationData.item($key)
    }
    $InputData | Out-file $newFilePath

    Input:

    Output:

    Hope that helps.

     

Resources