3

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?

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

This seems to be the answer I can understand the most. What does % { ($_ -split '"')[1] -split ' ' } do?
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.
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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.