Convert Arraylist to string in powershell

15,205

Solution 1

As mentioned in sean_m's comment, the easiest thing to do is to simply first convert the System.Collections.ArrayList of strings to a single string by using the -join operator:

$outputValue = $($outputValue -join [Environment]::NewLine)

Once you have done this you can perform any regular string operations on $outputValue, such as the Substring() method.

Above I separate each string in the ArrayList with a new line, as that's typically the string that the -OutVariable splits the string on when converting it to an ArrayList, but you can use a different separator character/string if you want.

Solution 2

Try like this:

$outputvalue = Select-String -inputObject $patternstring  -Pattern $regex -AllMatches | 
               % { $_.Matches } | % { $_.Value }
$outputValue | % { $_.Substring(1 ,$_.Length - 2)}

The parameter -outvariable in the ForEach-Object doesn't seem to capture the output of the sciptblock processed ( This in Powershell V2; thank to @ShayLevi for testing it works in V3).

Solution 3

If the output is a collection of values then no matter what the type of the result is , substring should fail. Try to pipe to Foreach-Object and then use substring.

UPDATE:

The OutputVariable works only in v3, see @Christian solution for v2.

Select-String -InputObject $patternstring  -Pattern $regex -AllMatches  | % { $_.Matches } | % { $_.Value } -OutVariable outputValue
$outputValue | Foreach-Object { $_.Substring(1,$_.Length-2) }
Share:
15,205
Nida Sahar
Author by

Nida Sahar

Just another Techie!

Updated on June 14, 2022

Comments

  • Nida Sahar
    Nida Sahar almost 2 years

    I am trying to grep some data from a variable:

     Select-String -inputObject $patternstring  -Pattern $regex -AllMatches
     | % { $_.Matches } | % { $_.Value } -OutVariable outputValue
     Write-Host $outputValue
    

    To the same outvariable, I am trying to do string manipulation

    $outputValue.Substring(1,$outputValue.Length-2);
    

    this fails stating that outputValue is an ArrayList.

    How can I convert an Arraylist to String?

  • CB.
    CB. over 11 years
    I tested this way but seem that in this foreach the -outvariable isn't populate. Can you confirm this issue? thanks
  • Shay Levy
    Shay Levy over 11 years
    You're right, I was testing on v3 and it worked. It failed in v2. In any case, the result is System.String, not ArrayList.
  • Shay Levy
    Shay Levy over 11 years
    +1, anyway, I think you need to pipe the result to foreach in case the result is a collection, otherwise substring will fail.
  • CB.
    CB. over 11 years
    @shayLevy Sure! Have forgot to paste the rigth command. Edited my answer.. again :)
  • CB.
    CB. over 11 years
    +1 But isn't it Foreach-Object { $_.Substring(1,$_.Length-2) } ?
  • Shay Levy
    Shay Levy over 11 years
    Correct again, it is fixed now :)