2013-05-03 80 views
1

一個文本文件,創建從值的數組我有這個內容的文本文件:在使用PowerShell

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

,我讀了另一個PowerShell腳本文件,我想創建WORKER_SEGMENTS值的數組。到目前爲止,我已經得到了:

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

這產生了:

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

我只需要worker01worker02worker03worker04WORKER_SEGMENTS(沒有領先#)作爲數組。我如何實現這一目標?

回答

2

你可以試試這個:

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

worker01 
worker02 
worker03 
worker04 

或者

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

worker01 
worker02 
worker03 
worker04 
+0

這似乎是我最能理解的答案。 '%{($ _ -split''')[1] -split''}是做什麼的? – mles 2013-05-03 15:59:02

+1

它在前兩個'''(這是workernames)之間獲取內容,然後它將名稱變成數組在空間上分裂。第一個樣本使用正則表達式做同樣的事情。 – 2013-05-03 16:12:47

0

你可能不得不調整它有點讓你想要什麼,但這應該讓你在正確的方向前進:

$workers = (Get-Content $strPath"\worker\conf\segments.conf" | ?{$_ -like 'Worker_Segments*'}).Split('"')[1].Split(' ') 
2

試試這個:

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

通過使用散列表,我們可以很容易地消除重複的條目。