array or hash table splitting

Welcome Forums General PowerShell Q&A array or hash table splitting

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years, 2 months ago.

  • Author
  • #5533

    Points: 0
    Rank: Member

    by veroli at 2013-02-11 04:08:48


    am having trouble splitting an array into multiple arrays
    I have a text file with server names that is split into sections these sections are defined like an INI file
    for example

    [server group 1]
    [server group 2]
    [server group 3]

    I want to read this file in and then split these sections into three seperate arrays so i can use them
    Its probably a really easy question but I can't seem to split them how i want after reading in from get-content.
    Should i split based on the [] and use a wildcard between them or is there a better way of handling this.


    by coderaven at 2013-02-11 07:48:09

    Someone may be better at this, but I think putting the data in a hash table would be best. Take the following as an example.

    $FileName = \\path\to\File.txt
    $Key = "Server Group X"
    $ResultContent = @{}

    $ArrContent = Get-Content -Path $FileName

    foreach ($Line in $ArrContent)
    $HeaderFound = $False
    If ($Line.StartsWith("[") { $Key = $Line; $HeaderFound = $True }
    if (!$HeaderFound) {$ResultContent.Add($Key, $Line)}

    It may be a little long for something so simple but it should work.

    by mjolinor at 2013-02-11 20:33:29

    If you really want variables:
    [code2=powershell]get-content serverlist.txt |
    foreach {
    if ($_ -match '\[.+\]')
    $var = $_.trim('[]').replace(' ','_')
    New-Variable $var
    else {set-variable -Name $var -value ((Get-Variable -Name $var).value += @($_))}

    get-variable server_*[/code2]

    Name Value
    —- —–
    server_group_1 {server1, server2, server3}
    server_group_2 {server8, server9, server10}
    server_group_3 {server13, server14, server15}

    by veroli at 2013-02-12 00:54:55

    thanks guys i will work from this much appreciated,
    i am also looking to see if it is more viable in an xml file might be easier to split it

The topic ‘array or hash table splitting’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort