在powershell中将Arraylist转换为字符串

在powershell中将Arraylist转换为字符串,powershell,Powershell,我试图从变量中提取一些数据: Select-String -inputObject $patternstring -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } -OutVariable outputValue Write-Host $outputValue 对于同一个输出变量,我尝试进行字符串操作 $outputValue.Substring(1,$outputValue.Length-2); 这无法说

我试图从变量中提取一些数据:

 Select-String -inputObject $patternstring  -Pattern $regex -AllMatches
 | % { $_.Matches } | % { $_.Value } -OutVariable outputValue
 Write-Host $outputValue
对于同一个输出变量,我尝试进行字符串操作

$outputValue.Substring(1,$outputValue.Length-2);
这无法说明outputValue
ArrayList

如何将
数组列表
转换为
字符串

试着这样做:

$outputvalue = Select-String -inputObject $patternstring  -Pattern $regex -AllMatches | 
               % { $_.Matches } | % { $_.Value }

$outputValue | % { $_.Substring(1 ,$_.Length - 2)}

ForEach对象中的参数
-outvariable
似乎没有捕获已处理sciptblock的输出(这在Powershell V2中;感谢@ShayLevi在V3中测试它的工作原理)。

如果输出是一组值,那么无论结果的类型是什么,子字符串都应该失败。尝试通过管道连接到每个对象,然后使用子字符串

更新:

OutputVariable仅适用于v3,请参见@Christian solution for v2

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

$outputValue | Foreach-Object { $_.Substring(1,$_.Length-2) }

正如sean_m的评论中提到的,最简单的方法是首先使用-join运算符将字符串的System.Collections.ArrayList转换为单个字符串:

$outputValue = $($outputValue -join [Environment]::NewLine)
完成此操作后,可以对$outputValue执行任何常规字符串操作,例如Substring()方法


上面我用一个新行分隔ArrayList中的每个字符串,因为在将字符串转换为ArrayList时,-OutVariable通常会在该字符串上拆分字符串,但如果需要,可以使用不同的分隔符字符/字符串。

我以这种方式进行了测试,但在这种情况下,
-OutVariable
似乎无法填充。你能确认这个问题吗?谢谢你说得对,我在v3上测试,它成功了。它在v2中失败了。在任何情况下,结果都是System.String,而不是ArrayList.+1,但它不是
Foreach对象{$\uU.Substring(1,$\uU.Length-2)}
?再次更正,它现在已修复:)+1,无论如何,我认为如果结果是集合,您需要将结果管道传输到Foreach,否则子字符串将失败。@shayLevy确定!忘记粘贴rigth命令了。编辑了我的答案。。再次说明:)您是否尝试过先对$outputValue执行联接?Ala$($outputValue-join“`t”)这将为您提供序列化为一个制表符分隔字符串的arraylist值。