powershell copy a string in one file to another

This topic contains 3 replies, has 2 voices, and was last updated by  Jamie 3 weeks, 6 days ago.

  • Author
    Posts
  • #80090

    Jamie
    Participant

    can you help me with find a some script to help me to replace a string from one to another file.
    for example in test1.xml i have string id="123", and i want to copy it to test2.xml instead of id="1" to be "123"

    i tried with some script:

    [code]
    # Original text
    $inputFile1 = "C:\ephemeral\file1.xml"
    # Text to be inserted
    $inputFile2 = "C:\ephemeral\file2.xml"
    # Output file
    $outputFile = "C:\ephemeral\file3.txt"
    # Find where the last tag is
    if ((Select-String -Pattern "uid=" -Path $inputFile1 |
    select -last 1) -match ":(/>\d+):")
    {
    $insertPoint = $Matches[1]
    # Build up the output from the various parts
    Get-Content -Path $inputFile1 | select -First $insertPoint | Out-File $outputFile
    Get-Content -Path $inputFile2 | Out-File $outputFile -Append
    Get-Content -Path $inputFile1 | select -Skip $insertPoint | Out-File $outputFile -Append
    }[/code]

    but i am not sure why he use 2 input and 1 output files. idont get it...

    ***Edited at the request of OP – WA***

  • #80101

    Don Jones
    Keymaster

    So, you could parse the XML and actually manipulate it programmatically, versus just doing a replace of a string. Have you worked with structured XML before?

  • #80134

    Jamie
    Participant

    there is no point of doing with xml because i have many pcs with IDs in that xml files, and everyone pc has different UID.
    So this is an action that I must do, and something else, but first i must put UID from old config file to another in the same UID string line.

  • #80138

    Jamie
    Participant

    i can with this

    Get-ChildItem 'test.xml' -Recurse | ForEach {
    (Get-Content $_ | ForEach { $_ -replace '[MYID]', 'MyValue' }) |
    Set-Content $_
    }
    but how can i use instead of 'MyValue' to use UID of another file?

You must be logged in to reply to this topic.