PowerShell从数组中删除项目[0] [英] PowerShell Remove item [0] from an array
问题描述
我正在努力删除数组的第一行(项目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的功能.我从 an MSDN博客文章:
It's been a feature of Powershell for over a decade. I found this functionality from an MSDN blog post:
这篇关于PowerShell从数组中删除项目[0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!