【问题标题】:What causes error in powershell when adding process to arrayList?将进程添加到arrayList时导致powershell出错的原因是什么?
【发布时间】:2017-01-20 20:06:37
【问题描述】:

我的代码

[System.Collections.ArrayList]$Global:shells=@()
$cmdProc = Start-Process powershell -ArgumentList "-noexit", ("-command grunt "+ [string]$argList) -WorkingDirectory $fwd -PassThru
[System.Collections.ArrayList]$Global:shells.Add(($cmdProc))

确实将 PowerShell 进程添加到 $shells arrayList。但它也会显示一条错误消息:

无法将“System.Int32”类型的“0”值转换为类型
“System.Collections.ArrayList”。
在行:16 字符:1
+ [System.Collections.ArrayList]$Global:shells.Add(($cmdProc))

它肯定与它添加的arrayList的索引有关,但这是怎么回事?我可以访问$shells[0] 就好了。

【问题讨论】:

    标签: powershell arraylist


    【解决方案1】:

    在最后一条语句中:

    [System.Collections.ArrayList]$Global:shells.Add(($cmdProc))
    

    PowerShell 尝试将 Add() 方法调用的输出(即 0,您刚刚插入的索引)转换为 ArrayList,因为前面有 [System.Collections.ArrayList] 文字。

    改成:

    [void]$Global:shells.Add(($cmdProc))
    

    【讨论】:

      【解决方案2】:

      在我看来,更好的解决方案是正确设置数组的类型,即:

      [System.Diagnostics.Process[]] $Global:shells = @();
      
      try {
          $shells += Start-Process powershell <blah blah> -PassThru;
          } #try
      catch [System.Exception] {
          # blah
          } #catch
      

      ...对于那些不熟悉 PowerShell 的人,-passthru 参数会导致 Start-Process cmdlet 返回它生成的对象。通常这样做是为了您可以使用此对象进一步推动 powershell“管道”。在 Start-Process 的情况下,它返回类型为 System.Diagnostics.Process 的对象,因此是静态数据类型分配。

      【讨论】:

      • 如果[System.Diagnostics.Process[]] 不是静态集合就可以了。对于需要添加人员的静态数组,我通常会尽量避免使用+=。实际上对我来说似乎有点不幸的是,powershell 基本数组类型本身不支持Add()Remove() 等方法......
      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2011-09-29
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2019-02-15
      相关资源
      最近更新 更多