在powershell中将变量拆分为动态多维表

问题描述 投票:0回答:1

我正在尝试将变量拆分为多维变量。我收到错误:“索引超出边界。”

我试图创建额外的变量 $table() 并以不同的方式声明它,但一切都失败了。

我的问题是变量 $tables 必须采用动态输入(可以有不同数量的表名称除以“:”和该表的坐标除以“,”)

我想要这样的输出:

$tables[0][0] = "tab_eposter"
$tables[0][1] = "2"
..
$tables[1][0] = "tab_befaring"
..
$tables[1][2] = 3

有人可以帮我吗?

function Get-Txt-From-Excel {
  
  Param(

    [Parameter(Mandatory)]
    $inFile,
    [Parameter(Mandatory)]
    $outFile,
    $ranges = "info_ordre,info_adresse",
    $tables = "tab_eposter,2,2,1,3,3,2:tab_befaring,2,3",
    $sheet = "prosjekt-info",
  )

  try{

    # Internal variables
    $ranges = $ranges -split ","
    $tables = $tables -split ":"
    
    for( $i = 0; $i -le $tables.length; $i++ ) {
      $tmp_table = $tables[$i] -split ","
      $tables[$i] = $tmp_table
    }

    Write-Host $tables[0][0]
    throw
...
powershell multidimensional-array dynamic
1个回答
0
投票

继续我的评论,我认为如果将结果收集到哈希表而不是多维数组中会更容易。

具体操作方法如下:

$tables = "tab_eposter,2,2,1,3,3,2:tab_befaring,2,3"

$tables = @($tables -split ":")  # use @() to force it as array
$result = @{}                    # create a Hashtable to store the results

for ( $i = 0; $i -lt $tables.Count; $i++ ) {
  $temp = $tables[$i] -split ","
  $name, $values = $temp         # split the temp array in the name (element [0]) and the numeric values
  $result[$name] = $values
}

然后您可以使用正常的点符号来引用该表及其值:

$result.tab_befaring  # --> an array with values 2 and 3
$result.tab_eposter   # an array with values 2 2 1 3 3 and 2
© www.soinside.com 2019 - 2024. All rights reserved.