【问题标题】:Simple string concatenation updating array in PowershellPowershell中的简单字符串连接更新数组
【发布时间】:2019-05-03 08:09:22
【问题描述】:

我在 Powershell 中有一个字符串数组。对于每个元素,我想将一个常量字符串与元素连接起来,并在相应的索引处更新数组。我要导入的文件是由换行符分隔的非空白字符串元素列表。

似乎没有发生更新数组元素的串联。

$Constant = "somestring"
[String[]]$Strings = Get-Content ".\strings.txt"

foreach ($Element in $Strings) {
  $Element = "$Element$Constant"
}

$Strings

导致以下输出:

Element
Element
...

根据 Powershell 中数组不可变的提示,我尝试使用连接值创建一个新数组。结果一样。

我错过了什么?

【问题讨论】:

    标签: arrays string powershell string-concatenation


    【解决方案1】:

    您将值连接到局部变量 $Element 但这不会更改变量 $Strings

    这是我的方法,将新值保存到$ConcateStrings。通过返回连接的字符串而不将其分配给局部变量,变量$ConcateStrings 将具有所有新值

    $Constant = "somestring"
    $Strings = Get-Content ".\strings.txt"
    
    $ConcateStrings = foreach ($Element in $Strings) {
        "$Element$Constant"
    }
    
    $ConcateStrings
    

    【讨论】:

      【解决方案2】:

      只是为了展示一个迭代数组索引的替代方法

      $Constant = "somestring"
      $Strings = Get-Content ".\strings.txt"
      
      for($i=0;$i -lt $Strings.count;$i++) {
        $Strings[$i] += $Constant
      }
      
      $Strings
      

      '.\strings.txt' 包含一、二、三的示例输出

      onesomestring
      twosomestring
      threesomestring
      

      【讨论】:

        猜你喜欢
        • 2010-11-19
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        • 2015-07-01
        • 2012-11-28
        • 2015-06-02
        • 2012-12-19
        • 1970-01-01
        相关资源
        最近更新 更多