2015-07-21 45 views
0

我试图建立将一个字符串数组分成 a)用[X]字符串数组 - 或 - b)中的字符串X数组一个哈希表的功能动态分割的阵列中的powershell

我现在拥有的是以下几点:

Function Split-Array { 
    Param (
     # Param1 help description 
     [Parameter(Mandatory=$true, 
        ValueFromPipelineByPropertyName=$true)] 
     [array]$arrToSplit, 

     # Param2 help description 
     [int]$SplitInTo = 8 
    ) 

     $Round = 0 
     $hashSplitted = @{} 

     For ($i = 0 ; $i -le ($SplitInTo -1) ; $i++) { 
      New-Variable -Name "arrPartial$i" -Value @() 
      } 

     While (($Round * $SplitInTo) -le $arrToSplit.Count) { 
      For ($i = 0 ; $i -le ($SplitInTo - 1) ; $i++) { 
       $arrDynamicVariable = Get-Variable -name "arrPartial$i" -ValueOnly 
       $arrDynamicVariable += $arrToSplit[($Round * $SplitInTo) + $i] 
       Set-Variable -Name "arrPartial$i" -Value $arrDynamicVariable 
       } 
      $Round++ 
      } 

     For ($i = 0 ; $i -le ($SplitInTo -1) ; $i++) { 
      $hashSplitted[$i] = Get-Variable -Name "arrPartial$i" -ValueOnly 
      } 
     $hashSplitted 
    } 

它似乎出问题的是“获取变量”的一部分。 PowerShell中给出了一个错误:

Get-Variable : Cannot find a variable with the name 'arrPartial8'. At line:1 char:1 + Get-Variable -name "arrPartial$i" -ValueOnly + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (arrPartial8:String) [Get-Variable], I temNotFoundException + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVari ableCommand

奇怪的是,arrPartial变量似乎被创建,但它是一个有点不同从例如声明的变量“$ ARRA = @()”,如下所示:

PS Variable:\> dir 

Name       Value             
----       -----             
$        )              
?        True             
^        $arra             
args       {}              
arra       {}              
arrPartial0     {}              
arrPartial1     {}              
arrPartial2     {}              
arrPartial3     {}              
arrPartial4     {}              
arrPartial5     {}              
arrPartial6     {}              
arrPartial7     {}         

通知的事实arrPartialx阵列具有其{}缩进到左边。这是一个错误还是我在这里做错了什么?任何想法,不同的方式来做到这一点是受欢迎的。

+1

我复制并粘贴这个,并运行对我自己的数组并没有这样的错误。你有没有尝试过新的控制台? – StegMan

回答

1

不知道我是否正确理解你想要达到的目标。你想“折叠”一维数组

[ a, b, c, d, e, f, g, h, i, j ] 

到这样一个哈希表(假设$SplitInTo = 3为简单起见)?

{ 
    arrPartial0 => [ a, d, g, j ] 
    arrPartial1 => [ b, e, h ] 
    arrPartial2 => [ c, f, i ] 
} 

如果是这样,你让这个方式太复杂了。像这样的东西应该就足够了:

function Invoke-FoldArray { 
    Param(
    [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)] 
    [array]$arrToSplit, 
    [int]$SplitInTo = 8 
) 

    $ht = [ordered]@{} 

    0..($SplitInTo-1) | % { 
    $ht["arrPartial$_"] = @() 
    } 

    $i = 0 
    $arrToSplit | % { 
    $ht["arrPartial$i"] += $_ 
    $i++ 
    $i %= $SplitInTo 
    } 

    return $ht 
} 
+1

你甚至可以用'[array] $ ht [“arrPartial $ i”] + = $ _'来分配,并且完全跳过第一个循环 –

+0

谢谢Ansgar Wiechers!这就是我正在寻找的东西:D –

+0

对不起,新的to stackoverflow。肯定解决了这个问题:) –