访问内容os 逐行变量在上电shell

Access content os variable line by line in power shell

我将命令的输出存储在一个变量中。 现在我想逐行访问它的内容。

$OutputVariable = (dir | % { $_.FullName -replace "C:\","" }) | Out-String;
$OutputVariable

输出如下:-

D:\ASGN5
D:\ASSIGNMENT 5

所以基本上我想要的是逐行访问变量的输出 就像首先我想要 D:\ASGN5

我们可以通过$$OutputVariable[0..n]

得到数据

但是我想知道有没有其他方法可以逐行访问它?

来自 the doc

By default, Out-String accumulates the strings and returns them as a single string, but you can use the stream parameter to direct Out-String to return one string at a time.

但你根本不必使用外串。 让我们通过 get-childitem (dir) 命令在对象 return 上使用 foreach 循环:

$OutputVariable = (dir | % { $_.FullName -replace "C:\","" })
$OutputVariable |foreach {"value is $_"}