Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Arraylist to string in powershell

Tags:

powershell

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?

like image 747
Nida Sahar Avatar asked Oct 26 '25 10:10

Nida Sahar


1 Answers

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.

like image 71
deadlydog Avatar answered Oct 29 '25 08:10

deadlydog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!