此行區分沒有冒號(服務器名)和線中的一個冒號(服務器屬性),並建立每個服務器的數據集,每次重置它得到一個新的服務器名稱的時間。
# For each line in the text file
Get-Content d:\data.txt | Foreach {
if ($_ -notmatch ':') { # Line is a server name, reset.
if ($server) { [pscustomobject]($server) } # Output dataset (skip 1 at beginning).
$server = [ordered]@{'Name'=$_.Trim()} # create new dataset.
} else { # Line is a server property
$key, $value = $_.split(':') # Process line.
$server[$key.Trim()] = $value.Trim() # Add details to dataset.
}
} | Export-Csv D:\data.csv -NoTypeInformation # Export, without PS Type details.
編輯:如果文件在最後一個換行符以上版本纔有效。如果文件末尾沒有換行符,邏輯相同,但此時switch
在具有冒號和行的行之間切換,並使用ForEach -End {}
塊輸出最後一個條目,則這是一個變體。
Get-Content D:\data.txt | ForEach { Switch -Regex ($_) {
':' {$key, $value = $_.Split(':'); $block[$key] = $value; break}
default {if ($block) {[pscustomobject]$block}; $block = [ordered]@{'Name'=$_ }}
}} -End {[pscustomobject]$block}
(是的,你可以把它攤開到20行,而不是4 ...或-End{}
塊添加到原)。
一般來說,展示你已經嘗試過的東西是個好主意。話雖如此,我已經發布了一個應該適合你的答案。 –