Text file manipulation question

Welcome Forums General PowerShell Q&A Text file manipulation question

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
1 week, 3 days ago.

  • Author
    Posts
  • #113416

    Participant
    Points: 0
    Rank: Member

    Hi All,

    I have a text file of 500+ FQDN server names. Example:

    servername1.domain.com

    servername2.domain.com

    servername3.domain.com

     

     

    I need to add the following entries for each servername:

    [servername1]

    parent=Group

    host=servername1.domain.com

     

    How would one go about doing this?

     

    Thanks in advance

     

     

     

  • #113645

    Participant
    Points: 0
    Rank: Member

    String manipulation is a very powerful tool. Really you have 4 steps to accomplish.

    1) Import your file, I'm choosing to do this with a get content

    2) Massage your data, this is really the tricky part. I really only need to break off the leaf name (and I did this using a split and grabbing the 0 index). Then it's just adding some string concatenation to add your brackets in.

    3) Write your output, this is simple once you've massaged it.

    4) Loop it

    
    $FQDNS = Get-Content FQDNFile.txt
    
    ForEach ($FQDN in $FQDNS)
    
    {
    
    $leaf = $FQDN.Split(".")[0]
    
    
    
    out-file -filepath "FQDNFile2.txt" -Append -inputobject "[$leaf]"
    
    out-file -filepath "FQDNFile2.txt" -Append -inputobject "parent=Group"
    
    out-file -filepath "FQDNFile2.txt" -Append -inputobject "host=$FQDN"
    
    }
    
    
  • #113657

    Participant
    Points: 0
    Rank: Member
    
    # Create an object for each server then export results to csv
    
    $server = Get-Content .\server.txt
    
    $result =
    
    foreach ($s in $server){
    
    [PSCustomObject]@{
    
    ServerName = $s -replace '.domain.com'
    
    host = $s
    
    parent = 'Group'
    
    }
    
    }
    
    $result | Export-Csv .\server.csv -NoTypeInformation
    
    
    • #113669

      Participant
      Points: 0
      Rank: Member

      Thanks Random Commandline!

       

      I ended up using below code (ThanksĀ Pedro Casalinho), but yours also seems to do the trick:

       

      $FQDNServers = Get-Content C:\Temp\FQDNServers.txt
      $Converted = @()
      foreach ($iFQDNServers in $FQDNServers) {
      $Output = @'
      [{0}]
      parent=Group
      host={1}
      '@ -f (($iFQDNServers.Split('.'))[0], $iFQDNServers)
      $Converted += $Output
      }
      $Converted | Set-Content c:\Temp\FQDNServersConverted.txt
      

       

       

      Thanks again for the help!

  • #113683

    Participant
    Points: 0
    Rank: Member

    duplicate post

You must be logged in to reply to this topic.