Creating an array from values in a text file with powershell

17,043

Solution 1

You can try this:

Get-Content .\t.txt | 
? { $_ -like "WORKER_SEGMENTS*" } | 
% { $_ -replace '.*?"([^"]*)".*', '$1' -split " " }

worker01
worker02
worker03
worker04

Or

Get-Content .\t.txt | 
? { $_ -like "WORKER_SEGMENTS*" } | 
% { ($_ -split '"')[1] -split ' ' }

worker01
worker02
worker03
worker04

Solution 2

Try this:

Get-Content $strPath"\worker\conf\segments.conf" | 
    Select-String 'WORKER_SEGMENTS\s*=\s*"([^"]*)"' | 
    Foreach {$_.Matches.Groups[1].Value -split ' '} | 
    Foreach {$ht=@{}}{$ht.$_=$null}
$ht

By using a hashtable we can eliminate duplicate entries fairly easily.

Solution 3

you may have to tweak it a bit to get exactly what you want, but this should get you headed in the right direction:

$workers = (Get-Content $strPath"\worker\conf\segments.conf" | ?{$_ -like 'Worker_Segments*'}).Split('"')[1].Split(' ')
Share:
17,043
mles
Author by

mles

Quality Assurance tester for kdice.com since 2008

Updated on June 29, 2022

Comments

  • mles
    mles over 1 year

    I have a text file with this content:

    SEGMENTS="worker01 worker02 worker03 worker04"
    WORKER_SEGMENTS="worker01 worker02 worker03 worker04"
    #SEGMENTS="worker01"
    #WORKER_SEGMENTS="worker01"
    

    I read this file from another powershell script and I want to to create an array of the WORKER_SEGMENTS values. I have gotten so far:

    $workers = Get-Content $strPath"\worker\conf\segments.conf" | Where-Object {$_ -like "*WORKER_SEGMENTS*"}
    Write-Host $workers
    

    This yields:

    PS Q:\mles\etl-i_test\rc> .\etl.ps1
    WORKER_SEGMENTS="worker01 worker02 worker03 worker04" #WORKER_SEGMENTS="worker01"
    

    I only need the worker01, worker02, worker03, worker04 from WORKER_SEGMENTS (without the leading #) as an array. How do I achieve this?

  • mles
    mles over 10 years
    This seems to be the answer I can understand the most. What does % { ($_ -split '"')[1] -split ' ' } do?
  • Frode F.
    Frode F. over 10 years
    It gets content between the first two " (which is the workernames), then it turns the names into an array by splitting on space. The first sample does the same using regex.