tags:

views:

207

answers:

3

Here is the deal, I am going through an INI file with some code. The idea is to return all of the categories found in the INI file with a regex, and then set at an arraylist = to results.

So here is the code:

    switch -regex -file $Path
    {
        "^\[(.+)\]$" {
            $arraylist.Add($matches[1])
        }
    }

However, the function returns not only the categories but also a count of the categories. For example, if the INI file looks like this:

[Red]
[White]
[Blue]

The output is:

0
1
2
Red
White
Blue

How can I fix this?

A: 

I'm trying to reproduce the problem you're seeing but cannot do it. Here is a recreation of the code that I'm using to test with:

("[Red]","[White]","[Blue]") | Out-File Test.ini -Encoding ASCII
$Path = (get-item Test.ini)
$arraylist = new-object System.Collections.ArrayList
$matches = @()
switch -regex -file $Path {
    "^\[(.+)\]$" {
     $arraylist.Add($matches[1]) 
    }
}

$arrayList

When this is executed, I get the following output:

Red   
White    
Blue

Is there something I'm missing that your code does not show?

Scott Saad
No idea why it didn't recreate it for you. It was doing what Keith said it was.Thanks.
lonewolfcoder
+3  A: 

ArrayList.Add() returns the index at which the item was added. This is why you see the numbers. Just cast that statement to void e.g.:

[void]$arraylist.Add($matches[1])

or pipe to Out-Null

$arraylist.Add($matches[1]) | Out-Null
Keith Hill
Thank you! I acutally just changed it to this:$index = $arraylist.Add($matches[1]) | Out-NullAnd that fixed it.
lonewolfcoder
You don't need to do both. If you capture the output in a variable like $index you no longer need to pipe to Out-Null.
Keith Hill
+1  A: 

Another option:

$al = new-object System.Collections.ArrayList
$cat = switch -regex -file $env:WINDIR\system.ini { "^\[([^\]]+)\]$" { $_ -replace '\[|\]'}}
$al.AddRange($cat)
Shay Levy
Note that in this version the `$cat` variable already contains the collection of results in an array, which has first-class support in PowerShell, making the ArrayList unnecessary. See also [Get-Help about_arrays](http://technet.microsoft.com/en-us/library/dd315313.aspx).
Emperor XLII