PowerShell 从数组中删除项目 [0] [英] PowerShell Remove item [0] from an array

查看:30
本文介绍了PowerShell 从数组中删除项目 [0]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力删除数组的第一行(项目 ID).

I'm struggling a bit to remove the first line (item ID) of an array.

$test.GetType()

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

列出我尝试过的所有选项 ,$test |gm 并明确指出:

To list all the options I tried ,$test | gm and it clearly states:

Remove         Method                void IList.Remove(System.Object value)                                                                                              
RemoveAt       Method                void IList.RemoveAt(int index)

所以当我尝试 $test.RemoveAt(0) 时,我得到了错误:

So when I try $test.RemoveAt(0) I get the error:

Exception calling "RemoveAt" with "1" argument(s): "Collection was of a fixed size."At line:1 char:1
+ $test.RemoveAt(1)
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException

所以我终于找到了这里我的数组需要是 System.Object 类型才能使用 $test.RemoveAt(0).将脚本开头的所有数组声明为列表是最佳实践吗?还是在需要此功能时将带有 $collection = ({$test}.Invoke()) 的数组转换为列表更好?

So I finally found here that my array needs to be of the type System.Object to be able to use $test.RemoveAt(0). Is it best practice to declare all the arrays in the beginning of the script as a list? Or is it better to convert the arrays with $collection = ({$test}.Invoke()) to a list later on when this functionality is needed?

这两种类型的优缺点是什么?感谢您的帮助.

What are the pro's and cons of both types? Thank you for your help.

推荐答案

另一种选择是使用 Powershell 的功能分配多个变量(参见这个其他答案).

An alternative option is to use Powershell's ability to assign multiple variables (see this other answer).

$arr = 1..5
$first, $rest= $arr

$rest
2
3
4
5

十多年来,它一直是 Powershell 的一个功能.我从 一篇 MSDN 博文:

It's been a feature of Powershell for over a decade. I found this functionality from an MSDN blog post:

这篇关于PowerShell 从数组中删除项目 [0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆