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?
ArrayList.Add() returns the index at which the item was added. This is why you see the numbers. Just cast that statement to void eg:
[void]$arraylist.Add($matches[1])
or pipe to Out-Null
$arraylist.Add($matches[1]) | Out-Null
Another option:
$al = new-object System.Collections.ArrayList
$cat = switch -regex -file $env:WINDIR\system.ini { "^\[([^\]]+)\]$" { $_ -replace '\[|\]'}}
$al.AddRange($cat)
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.