Creating Variables From middle of text file line

Welcome Forums General PowerShell Q&A Creating Variables From middle of text file line

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

2 years, 3 months ago.

  • Author
  • #68517

    Topics: 15
    Replies: 26
    Points: 0
    Rank: Member

    So I'm trying to create a script to audit any number of servers at our different customer locations. All of the information I'm looking for can be extracted from the config and xml files for our program, and the files are saved to a standard location. I'm able to use

    $data = Get-Content "C:\MyFolder\MyConfig.Config

    To get the 3rd line of the text. But let's say the contents of that line are:


    I'm trying to find a way to display different outputs with just "HOSTNAME\INSTANCE," "DATABASENAME," "DATABASEUSER," and "DATABASEPASSWORD."

    Any thoughts?

  • #68526

    Topics: 9
    Replies: 387
    Points: 500
    Helping Hand
    Rank: Contributor
    # For demo:
    $Lines = 'value="Data Source=HOSTNAME\INSTANCE1;Initial Catalog=DATABASENAMEx;User Id=DATABASEUSER3;Password=DATABASEPASSWORD6',
             'value="Data Source=HOSTNAME\INSTANCE2;Initial Catalog=DATABASENAMEy;User Id=DATABASEUSER4;Password=DATABASEPASSWORD7',
             'value="Data Source=HOSTNAME\INSTANCE3;Initial Catalog=DATABASENAMEz;User Id=DATABASEUSER5;Password=DATABASEPASSWORD8'
    # In your case you may use:
    # $Lines = Get-Content 'C:\MyFolder\MyConfig.Config'
    $MyOutput = $Lines | % {
            DataSource     = $_.Split(';')[0].Split('=')[1]
            InitialCatalog = $_.Split(';')[1].Split('=')[1]
            UserID         = $_.Split(';')[2].Split('=')[1]
            Password       = $_.Split(';')[3].Split('=')[1]
    $MyOutput | FT -a # output to console
    $MyOutput | out-gridview # in ISE
    $MyOutput | Export-Csv .\myOutput.csv -not 
  • #68607

    Topics: 15
    Replies: 26
    Points: 0
    Rank: Member

    Thank you! That helped a lot! Unfortunately I found that different versions of our program had slightly different config files so I had to add in a bunch of If statements, but I finally got it to display exactly as I wanted, and now that I better understand the split command, I feel like I'm on top of the world!

The topic ‘Creating Variables From middle of text file line’ is closed to new replies.