mles
mles

Reputation: 3466

Creating an array from values in a text file with powershell

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?

Upvotes: 3

Views: 18099

Answers (3)

Keith Hill
Keith Hill

Reputation: 201652

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.

Upvotes: 2

Frode F.
Frode F.

Reputation: 54881

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

Upvotes: 3

EBGreen
EBGreen

Reputation: 37730

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(' ')

Upvotes: 1

Related Questions