7

我在 Powershell 中遇到了一个有趣的问题,但一直无法找到解决方案。当我谷歌(并找到类似这篇文章的东西)时,没有什么比我想做的更重要,所以我想我会在这里发布这个问题。

该问题与外部数组长度为 1 的多维数组有关。看来 Powershell 非常坚持像@( @('A') )变得一样扁平化数组@( 'A' )。这是第一个片段(提示是>,顺便说一句):

> $a =  @( @( 'Test' ) )
> $a.gettype().isarray
True
> $a[0].gettype().isarray
False

所以,我希望$a[0].gettype().isarray是真的,这样我就可以将值索引为$a[0][0](现实世界的场景是在循环内处理动态数组,我想将值作为$a[$i][$j],但如果内部项目是不被识别为数组而是字符串(在我的情况下),您开始索引到字符串的字符,如$a[0][0] -eq 'T')。

我有几个长代码示例,所以我在最后发布了它们。而且,作为参考,这是在安装了 PSv2 和 PSCX 的 Windows 7 Ultimate 上。

考虑代码示例 1:我使用 += 运算符手动构建了一个简单的数组。中间数组$w被展平,因此没有正确添加到最终数组中。我在网上找到了类似问题的解决方案,基本上涉及在内部数组之前放置一个逗号以强制外部数组不变平,这确实有效,但是我正在寻找一种可以在循环内构建数组的解决方案(一个锯齿状数组数组,处理一个 CSS 文件),所以如果我将前导逗号添加到单个元素数组(实现为中间数组$y),我想对其他数组(如$z)做同样的事情,但这会产生不利影响如何$z添加到最终数组中。

现在考虑代码示例 2:这更接近我遇到的实际问题。当从函数返回具有一个元素的多维数组时,它会被展平。在它离开函数之前是正确的。同样,这些是示例,我真的在尝试处理文件而不必知道该函数是否会返回@( @( 'color', 'black') )或返回@( @( 'color', 'black'), @( 'background-color', 'white') )

有没有人遇到过这个问题,有没有人解决过这个问题?我知道我可以实例化框架对象,并且我假设如果我创建一个对象 []、一个列表 <> 或其他类似的东西,一切都会好起来的,但我已经处理了一些事情确实似乎必须有正确的方法来做到这一点(无需实例化真正的框架对象)。

代码示例 1

function Display($x, [int]$indent, [string]$title)
{
  if($title -ne '') { write-host "$title`: " -foregroundcolor cyan -nonewline }
  if(!$x.GetType().IsArray)
  { write-host "'$x'" -foregroundcolor cyan }
  else
  {
    write-host ''
    $s = new-object string(' ', $indent)
    for($i = 0; $i -lt $x.length; $i++)
    {
      write-host "$s[$i]: " -nonewline -foregroundcolor cyan
      Display $x[$i] $($indent+1)
    }
  }
  if($title -ne '') { write-host '' }
}


### Start Program
$final = @( @( 'a', 'b' ), @('c'))
Display $final 0 'Initial Value'

### How do we do this part ??? ###########
                                        ##
$w = @( @('d', 'e') )                   ##
$x = @( @('f', 'g'), @('h') )           ##
# But now $w is flat, $w.length = 2     ##
                                        ##
                                        ##
# Even if we put a leading comma (,)    ##
# in front of the array, $y will work   ##
# but $w will not. This can be a        ##
# problem inside a loop where you don't ##
# know the length of the array, and you ##
# need to put a comma in front of       ##
# single- and multidimensional arrays.  ##
$y = @( ,@('D', 'E') )                  ##
$z = @( ,@('F', 'G'), @('H') )          ##
                                        ##
                                        ##
##########################################

$final += $w
$final += $x
$final += $y
$final += $z
Display $final 0 'Final Value'


### Desired final value: @( @('a', 'b'), @('c'), @('d', 'e'), @('f', 'g'), @('h'), @('D', 'E'), @('F', 'G'), @('H') )
### As in the below:
# 
# Initial Value:
# [0]:
#  [0]: 'a'
#  [1]: 'b'
# [1]:
#  [0]: 'c'
# 
# Final Value:
# [0]:
#  [0]: 'a'
#  [1]: 'b'
# [1]:
#  [0]: 'c'
# [2]:
#  [0]: 'd'
#  [1]: 'e'
# [3]:
#  [0]: 'f'
#  [1]: 'g'
# [4]:
#  [0]: 'h'
# [5]:
#  [0]: 'D'
#  [1]: 'E'
# [6]:
#  [0]: 'F'
#  [1]: 'G'
# [7]:
#  [0]: 'H'

代码示例 2

function Display($x, [int]$indent, [string]$title)
{
  if($title -ne '') { write-host "$title`: " -foregroundcolor cyan -nonewline }
  if(!$x.GetType().IsArray)
  { write-host "'$x'" -foregroundcolor cyan }
  else
  {
    write-host ''
    $s = new-object string(' ', $indent)
    for($i = 0; $i -lt $x.length; $i++)
    {
      write-host "$s[$i]: " -nonewline -foregroundcolor cyan
      Display $x[$i] $($indent+1)
    }
  }
  if($title -ne '') { write-host '' }
}



function funA()
{
  $ret = @()
  $temp = @(0)
  $temp[0] = @('p', 'q')
  $ret += $temp
  Display $ret 0 'Inside Function A'
  return $ret # What about return ,$ret ? What about if $ret = @( @('p', 'q'), @('r', 's') ) -- would return ,$ret still work?
}

function funB()
{
  $ret = @( ,@('r', 's') )
  Display $ret 0 'Inside Function B'
  return $ret
}


### Start Program

$z = funA
Display $z 0 'Return from Function A'
$z = funB
Display $z 0 'Return from Function B'


### Desired final value: @( @('p', 'q') )  and same for r,s
### As in the below:
# 
# Inside Function A:
# [0]:
#  [0]: 'p'
#  [1]: 'q'
# 
# Return from Function A:
# [0]:
#  [0]: 'p'
#  [1]: 'q'

谢谢,马特

4

2 回答 2

7

还有另一个问题始于相同的问题:Powershell 陷阱。看起来这是设计使然。

我认为如果你 return,$ret而不是$ret,它应该可以工作。

还有两个注意事项:

  • 你可以测试,如果项目是数组$item -is [array](只是因为它看起来更像 PowerShell ;)
  • @()仅对不是数组的项目有效。如果您使用 chain @(@(@(1))),您将获得一个包含一个 int 项的数组(@(@(@(1)))[0].gettype()返回 Int32)。
    所以,@( ,@('r', 's') )是一样的,@('r', 's')
于 2010-03-17T21:20:30.040 回答
0

我使用以下示例尝试了 stej 所说的,并且成功了:

function funC([int]$numOfPairs)
{
  $ret = @()
  if($numOfPairs -eq 1)
  { $ret = ,@('r','s') }
  elseif($numOfPairs -eq 2)
  { $ret = @('r','s'),@('t','u') }
  else
  { $ret = @('r','s'),@('t','u'),@('v','w') }

  Display $ret 0 "Inside Function C ($numOfPairs)"
  return ,$ret
}


### Start Program

$z = funC 1
Display $z 0 'Return from Function C(1)'
$z = funC 2
Display $z 0 'Return from Function C(2)'
$z = funC 3
Display $z 0 'Return from Function C(3)'
于 2010-03-19T13:09:44.830 回答