My Find and Replace script is only working for the last pair of values from my csv file RRS feed

  • Question

  • $map = "/Users/myou4511/Documents/mapping.csv"
    $find = import-csv $map |
    Select-Object -ExpandProperty Find
    $replace = import-csv $map |
    Select-Object -ExpandProperty Replace
    $count = get-content $map | Measure-Object -Line
    $max = $count.lines -2
    Write-Output $max
    $files = Get-ChildItem -Path "/Users/myou4511/Documents/Test" -Recurse -File
    foreach ($file in $files){
    $content = Get-Content $($file.FullName)
    $x = 0
    while ($x -le $max) {
    Write-Output $find[$x] $replace[$x]
    $content -ireplace $find[$x],$replace[$x] | Out-File $($file.FullName)
    Write-Output $content
    $x = $x + 1

    I added some Write-Output lines to try and help, but I am stuck

    My csv file consists of :

    Find Replace
    blue name
    computer server
    his her

    • Moved by Bill_Stewart Thursday, January 25, 2018 10:08 PM Unanswerable drive-by question
    Wednesday, November 8, 2017 1:17 PM

All replies

  • Please format and post you code correctly.  It is hard to read.  Post with posting tool as it will remove HTML formatting so code can be correctly copied.


    Wednesday, November 8, 2017 1:23 PM
  • What I can figure out looking at you badly broken code is that you need to start by learning basic PowerShell.  Most of what you have posted makes no technical sense.

    Format the code correctly and you will begin to see why it is so badly broken.

    You cannot learn PowerShell by guessing.

    Learn PowerShell: https://mva.microsoft.com/en-us/training-courses/getting-started-with-microsoft-powershell-8276


    Wednesday, November 8, 2017 1:28 PM
  • I think this is what you are trying to do:

    $csv = import-csv ./Users/myou4511/Documents/mapping.csv
    $files = Get-ChildItem -Path ./Users/myou4511/Documents/Test -Recurse -File
    foreach ($file in $files) {
        $content = Get-Content $file
        $csv | 
                Write-Output $_.Find $_.Replace
                $content = $content -replace $_.Find, $_.Replace 
        $content | Out-File $file

    Notice that, if you know PowerShell, things are much easier.


    • Edited by jrv Wednesday, November 8, 2017 1:36 PM
    Wednesday, November 8, 2017 1:35 PM