powershell - 在PowerShell中声明包含另一个变量名称的变量(名称)

标签 powershell

我被困在这里:

$file = gci C:\...\test\ | %{$_.name}
for ($i=0; $i -lt 100; $i++) {
  $array_$i =  gc C:\...\test\$($file[$i])
}

我只是想为目录中的每个文本文件创建多个数组。

除了声明数组名称为$array_$i之外,其他一切工作正常。

最佳答案

我个人将选择已经提出的建议之一。使用某种收集数据结构通常会大大简化处理许多不同但相似的项目的过程。

  • 创建一个array of arrays:
    $array = @()
    Get-ChildItem C:\...\test | Select-Object -First 100 | ForEach-Object {
      $array += ,@(Get-Content $_.FullName)
    }
    

    在数组子表达式中运行Get-Content调用,并在其前面加上一元逗号运算符,可确保您添加一个嵌套数组,而不是每个元素都单独添加:

    [
      [ 'foo', 'bar', ... ],
      [ 'baz', ... ],
      ...
    ]
    

    而不是

    [
      'foo',
      'bar',
      'baz',
      ...
    ]
    
  • 创建一个hashtable of arrays:
    $ht = @{}
    Get-ChildItem C:\...\test | Select-Object -First 100 | ForEach-Object {
      $ht[$_.Name] = Get-Content $_.FullName
    }
    

    如果您需要能够通过特定键(在此示例中为文件名)而不是索引来查找内容,则最好使用哈希表。

    {
      'something': [ 'foo', 'bar', ... ],
      'other':     [ 'baz', ... ],
      ...
    }
    

    请注意,如果文件名重复,则必须选择其他键(例如,在不同的子文件夹中)。

  • 但是,如果由于某种原因必须为每个内容数组创建单独的变量,则可以使用 New-Variable cmdlet进行操作:
    $i = 0
    Get-ChildItem C:\...\test | Select-Object -First 100 | ForEach-Object {
      New-Variable -Name "array_$i" -Value (Get-Content $_.FullName)
      $i++
    }
    

    关于powershell - 在PowerShell中声明包含另一个变量名称的变量(名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539881/

    相关文章:

    TFS 构建定义中的 Powershell 脚本

    string - Powershell函数捕获字符串长度而不返回/换行

    regex - 使用 powershell 验证模式后获取下一个字符串

    arrays - 用PowerShell上另一个数组中的元素替换数组中的元素

    powershell - 在不知道 PowerShell 中的完整路径的情况下访问特定文件夹

    powershell - 使用 $null splat 参数时,Powershell 何时遵守默认值?

    powershell - 在 PowerShell 中使用 Connect-ExchangeOnline 命令时出现 New-ExoPSSession 错误

    PowerShell 数学错误

    powershell - Azure VM 设置中的 DefaultWinRMCertificateThumbprint 字段为空

    Regex Group,捕获 IP 的问题