簡體   English   中英

Powershell根據元素數量返回不同的數據類型

[英]Powershell returns different datatype depending on number of elements

當前,我對Powershell及其如何處理Arrays / ArrayLists和PSObjects / CustomObjects感到非常困惑。

高水平:

我正在嘗試導入CSV文件並在特定行插入“占位符”條目。 這實際上工作正常。 此刻我唯一的問題是,如果CSV僅包含1個元素(線),Powershell將創建一個PsCustomObject 如果有多行,Powershell將提供一個陣列。

$ pConnectionsOnMpDevice中的1個元素

$pConnectionsOnMpDevice  = ($pList | ?({$_.device -like "*$pDevice*"}))
($pConnectionsOnMpDevice).getType()

IsPublic IsSerial Name BaseType
True True PsCustomObject[] System.Object

$pConnectionsOnMpDevice n元素

$pConnectionsOnMpDevice  = ($pList | ?({$_.device -like "*$pDevice*"}))
($pConnectionsOnMpDevice).getType()

IsPublic IsSerial Name BaseType
True True Object[] System.Array

最后,我嘗試添加一個元素:

$pConnectionsOnMpDevice += $MpObject

(我的第一種方法是使用(FYI):

#$pConnectionsOnMpDevice.Insert($index,$match)

如果我嘗試將$MpObject添加到$pConnectionsOnMpDevice以下錯誤:

Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At C:\Scripts\PS_GenerateMPConfig\PS_GenerateMPConfig_06_f.ps1:90 char:13
+             $pConnectionsOnMpDevice += $MpObject
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

我認為這是與此處所述相同的問題

我試圖通過以下方式將$pConnectionsOnMpDevice轉換為Arraylist

[System.Collections.ArrayList]::$pConnectionsOnMpDevice  += $MpObject

但是仍然沒有成功。

有沒有人建議我如何添加元素?

使用數組子表達式運算符( @() )強制值表達式返回數組:

$pConnectionsOnMpDevice  = @($pList | ?({$_.device -like "*$pDevice*"}))

我試圖通過以下方式將$ pConnectionsOnMpDevice強制轉換為Arraylist:

 [System.Collections.ArrayList]::$pConnectionsOnMpDevice += $MpObject 

這不是"$pConnectionOnMpDevice"靜態調用"$pConnectionOnMpDevice"將調用與"$pConnectionOnMpDevice"同名的任何靜態方法或屬性。

如果要進行強制轉換操作,請刪除::

$array = 1,2,3
$arraylist = [System.Collections.ArrayList]$array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM