获取PSObject数组的大小或计数

时间:2019-03-08 14:02:20

标签: powershell psobject

我创建一个像这样的数组:

$Array = @()

$Item = New-Object PSObject
$Item | Add-Member -Type NoteProperty -Name item1 -Value test
$Item | Add-Member -Type NoteProperty -Name item2 -Value test

$Array += $Item

现在,我想添加一个检查以确定$Item是否为空,然后再将其添加到$Array中。如何获得$Item的成员数?

我尝试过类似的事情:

$Item.count
$Item.length
@($Item).count
($Item | Measure).count
($Item | Get-Member).count
$Item.psobject.members.count

但是他们都没有给我实际的会员人数。

3 个答案:

答案 0 :(得分:1)

您可以使用隐藏的.PsObject.Properties进行检查

$Item.PSobject.Properties.Value.count
$Item.PSobject.Properties.Names.count

$Item = New-Object PSObject
$Item.Psobject.Properties.value.count
0

$Item | Add-Member -Type NoteProperty -Name item1 -Value test
$Item.Psobject.Properties.value.count
1

$Item | Add-Member -Type NoteProperty -Name item2 -Value test
$Item.Psobject.Properties.value.count
2

答案 1 :(得分:0)

正确的方法是:

($Item|Get-Member -Type NoteProperty).count

答案 2 :(得分:0)

以下img_wishlist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RequestQueue req = Volley.newRequestQueue(context); StringRequest sr = new StringRequest(Request.Method.POST,Konfigurasi.url_wishlist_update, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jo = new JSONObject(response); String status = jo.getString("status"); if (status.equals("added")){ Toast.makeText(context,"added to your wishlist",Toast.LENGTH_SHORT).show(); //<---- here change resource image img_wishlist.setImageResource(R.drawable.icon_wishlist_full); }else{ Toast.makeText(context,"removed from your wishlist",Toast.LENGTH_SHORT).show(); //<---- here change resource image img_wishlist.setImageResource(R.drawable.icon_wishlist_o); } }catch (JSONException e){ e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override protected Map<String,String> getParams(){ Map<String,String> parang = new HashMap<String, String>(); parang.put("id_produk",id_produk.get(position)); parang.put("id_member",id_member); return parang; } }; req.add(sr); } }); 函数可以提供帮助:

Get_ItemCount

输出

Function Get_ItemCount {
    $aux = $($item | Get-Member -MemberType NoteProperty)
    if ( $aux -eq $null ) {
        0
    } elseif ( $aux -is [PSCustomObject] ) {
        1
    } else {
        $aux.Count
    }
}

$Item = New-Object PSObject
Get_ItemCount                  # 0
$Item | Add-Member -Type NoteProperty -Name item1 -Value test
Get_ItemCount                  # 1
$Item | Add-Member -Type NoteProperty -Name item2 -Value test
Get_ItemCount                  # 2