-replace multiple text and save

Tagged: 

This topic contains 3 replies, has 3 voices, and was last updated by  random commandline 1 week, 3 days ago.

  • Author
    Posts
  • #79918

    Tony Antony
    Participant

    I'm tryin to write a script that gets info from active directory to create outlook signatures.
    I'm able to get the info from ad, but the problem is that, when I do a -replace, it will only save the one for 'CELL', all the others above are not changed or saved in the text file. What am I doing wrong?

    $readCode = Get-Content $code
    
    $readCode -replace 'NAME', $fullName | Set-Content -Path $code -Force
    $readCode -replace 'TITLE', $jobTitle | Set-Content -Path $code -Force
    $readCode -replace 'STREET ADDRESS', $streetAddress | Set-Content -Path $code -Force
    $readCode -replace 'ADDRESS', $address | Set-Content -Path $code -Force
    $readCode -replace 'PHONE', "Phone $deskPhone" | Set-Content -Path $code -Force
    $readCode -replace 'CELL', "Cell $cellPhone" | Set-Content -Path $code -Force
    

    This is what the text file looks like, but I want every thing to change, not just 'CELL'

    NAME
    TITLE

    STREET ADDRESS
    ADDRESS
    PHONE
    Cell 555-555-5555

  • #79921

    Rick
    Participant

    You are reading the file multiple times and it's only processing the last line. You can do all the replaces on one line and set the content.

    $readCode.Replace("NAME",$fullName).Replace("TITLE",$jobTitle).Replace("STREE ADDRESS", $streetAddress).Replace("ADDRESS", $address).Replace("PHONE", $deskPhone).Replace("CELL", "CELL $cellPhone") | set-content $code
    
  • #79924

    Tony Antony
    Participant

    Thank you Rick,

    Tony

  • #79927

    random commandline
    Participant

    I would recommend a switch statement if your file is large.

    $file = Get-ChildItem .\Desktop\myfile1.txt
    
    $result = 
    switch -File $file {
       'name' {$_ -replace 'name',$fullname}
       'TITLE' {$_ -replace 'TITLE', $jobTitle} 
       'STREET ADDRESS' {$_ -replace 'STREET ADDRESS', $streetAddress}
       'ADDRESS' {$_ -replace 'ADDRESS', $address}
       'PHONE' {$_ -replace 'PHONE', "Phone $deskPhone"}
       'CELL' {$_ -replace 'CELL', "Cell $cellPhone"}
       Default {$_}
    }
    
    Set-Content -Path .\Desktop\myfile2.txt -Value $result
    

You must be logged in to reply to this topic.