Powershell 中的基本串联不起作用

Basic concatenation in Powershell doesn't work

我无法推送到 $filepaths,不明白为什么 :

$filepaths=@()
$files= @('file1.text','file2.txt')
foreach ($file in $files) {
  $filepaths.add("c:\test\" + $file)
}
$filepaths

@()System.Array (a fixed collection), reading from Remarks on the .Add method 从这个 Class:

Ordinarily, an IList.Add implementation adds a member to a collection. However, because arrays have a fixed size (the IsFixedSize property always returns true), this method always throws a NotSupportedException exception.

PowerShell 为我们提供了使用+= operator, however this is not recommended for reasons very well explained in .[=28=用新元素重新创建数组的能力]

您可以将枚举的输出分配给变量:

$filepaths = foreach($file in 'file1.txt', 'file2.txt') {
    "c:\test\" + $file
}
$filepaths

在此示例中,PowerShell 将为 $filepaths 动态分配类型,如果从枚举中返回 1 个元素,则它将是 string,对于多个它会变成 object[] (Array).

或者使用允许添加新元素的集合,例如ArrayList or List<T>:

$filepaths = [Collections.Generic.List[string]]::new()
foreach($file in 'file1.txt', 'file2.txt') {
    $filepaths.Add("c:\test\" + $file)
}
$filepaths

在这里,$filepaths 总是 List`1 类型。