代码之家  ›  专栏  ›  技术社区  ›  kervin

Powershell脚本在访问Array.Length属性后失败

  •  7
  • kervin  · 技术社区  · 15 年前

    有人能解释为什么这个脚本会抛出异常吗?

    $byteArray = @(1,2,3)
    write-Output ( "{0:X}{1:X}{2:X}" -f $byteArray )
    write-Output ( $byteArray.Length -ge 3 )
    write-Output ( "{0:X}{1:X}{2:X}" -f $byteArray )
    

    基本上,我创建一个数字数组,格式化数组,然后检查其长度并再次格式化。

    第一种格式成功,但第二种格式引发异常。

    123
    True
    --------------------------------------------------------------------------------
    POWERSHELL EXCEPTION 
    EXCEPTION TYPE:System.Management.Automation.RuntimeException
    MESSAGE:Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list..
    POSITION:
    At line:4 char:36
    + write-Output ( "{0:X}{1:X}{2:X}" -f  <<<< $byteArray )
    --------------------------------------------------------------------------------
    
    3 回复  |  直到 10 年前
        1
  •  4
  •   dahlbyk    15 年前

    要添加到谜题中:

    PS > $a = @(1,2,3)
    PS > $b = $a
    PS > [object]::ReferenceEquals($a, $b)
    True
    PS > $a.Length
    3
    PS > [object]::ReferenceEquals($a, $b)
    True
    PS > "{0:X}{1:X}{2:X}" -f $a
    Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argum
    ent list..
    At line:1 char:21
    + "{0:X}{1:X}{2:X}" -f  <<<< $a
    PS > "{0:X}{1:X}{2:X}" -f $b
    123
    PS > $b.GetLength(0)
    3
    PS > "{0:X}{1:X}{2:X}" -f $b
    123
    PS > [object]::ReferenceEquals($a, $b)
    True
    

    我倾向于同意贾里德的观点,这是一种怪癖 -f 运算符将变量视为对象而不是数组,部分原因如下:

    PS > $a = @(1,2,3)
    PS > "{0:X}{1:X}{2:X}" -f $a
    123
    PS > "{0:X}{1:X}{2:X}" -f $a.PSObject
    Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argum
    ent list..
    At line:1 char:21
    

    $a -f 快乐的但这仍然不能解释为什么要打电话 GetLength() $b “Arraynes”的方式是 Length (及 Rank )似乎是。

    @() 它似乎一直在工作。

        2
  •  3
  •   Joey Gumbo    15 年前

    这真奇怪。作为一种解决方法,您可以使用

    "{0:X}{1:X}{2:X}" -f @($byteArray)
    

    即使在访问 $byteArray

    另一种可能的解决方法是将格式化字符串保存到变量中并重新使用它。

    至于为什么在访问 Length 我不知道。

        3
  •  1
  •   JaredPar    15 年前

    哇,那太迷人了。我已经在PowerShell V2上对此进行了几分钟的讨论,我找不到一个确切的原因来解释为什么会发生这种情况。

    问题是-f命令实际上需要一个对象数组。问题行中明显出现的情况是,它将$byteArray解释为单个元素而不是数组。

    但是为什么它第一次起作用呢?我的 怀疑

    同样,这主要只是猜测。我强烈建议您在connect上提交一个bug,因为这闻起来像个bug。