添加元素添加到数组的PowerShell功能 [英] Powershell function for adding elements to an array
问题描述
我还是很新的PowerShell和试图创建创建与管理一个阵列整合了一些功能。而我在与获得这些功能之一是为了工作的一些问题。
I'm still quite new to Powershell and trying to create a few functions that weaves together for creating and administrating a array. And I'm having some problems with getting one of these functions to work as intended.
我需要什么样的第二个函数(AddToArray)也做的是一个元素添加到指定的索引。现有的元素都不能被覆盖或删除。
What I need the second function (AddToArray) too do is to add a element to the specified index. None of the existing elements can be overwritten or removed.
例如,如果我有4个指标的数组,并都值5,而我调用该函数AddToArray 2 4.我需要的功能在第三索引编写和移动现有的一跌步骤,以便数组现在看起来是这样的:
For example if I have an array with 4 indexes and all have the value 5 and I call the function AddToArray 2 4. I need the function to write for in the third index and move the existing ones one down step so the array now looks like this:
5
5
4
5
5
这是我的code到目前为止,显示我的CreateArray功能和小code片为AddToArray功能。我一直想有一段时间了,但我看不到解决方案。
This is my code so far that shows my CreateArray function and the little code piece for AddToArray function. I've been trying for a while now, but I just can't see the solution.
function CreateArray($Item1, $Item2)
{
$arr = New-Object Array[] $Item1;
# Kontrollerar om $Item2 har fått någon input och skriver in det i arrayen
if ($Item2)
{
for($i=0; $i -lt $arr.length; $i++)
{
$arr[$i]=$Item2;
}
}
# Standard värde på arrayens index om inget värde anges vid funktionens anrop
else
{
$Item2 = "Hej $env:username och välkommen till vårat script!";
for($i=0; $i -lt $arr.length; $i++)
{
$arr[$i]=$Item2;
}
}
$script:MainArray = $arr;
}
function AddToArray ($index, $add)
{
$MainArray[$index] = $add;
}
所有的帮助是AP preciated!
All help is appreciated!
有一个愉快的一天!
推荐答案
在.NET数组不直接支持插入和它们通常固定大小。 PowerShell中确实允许容易阵列调整,但如果数组变大,并要追加(导致一个调整大小)很多,性能可不好。
Arrays in .NET don't directly support insertion and they are normally fixed size. PowerShell does allow for easy array resizing but if the array gets large and you're appending (causing a resize) a lot, the performance can be bad.
一个简单的方法做你想做的是创建的作品例如一个新的数组:
One easy way to do what you want is to create a new array from the pieces e.g.:
if ($index -eq 0) {
$MainArray = $add,$MainArray
}
elseif ($index -eq $MainArray.Count - 1) {
$MainArray += $add
}
else {
$MainArray = $MainArray[0..($index-1)], $add, $MainArray[$index..($MainArray.Length-1)]
}
但是,这是怎样的一个溢料的。我会用这个列表,它支持插入和比数组更有效。
But that is kind of a spew. I would use a List for this, which supports insertion and is more efficient than an array.
$list = new-object 'System.Collections.Generic.List[object]'
$list.AddRange((1,2,3,4,5))
$list.Insert(2,10)
$list
如果你真的需要一个数组,调用 $ list.ToArray()
方法大功告成操纵列表时。
And if you really need an array, call the $list.ToArray()
method when you're done manipulating the list.
这篇关于添加元素添加到数组的PowerShell功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!