For writing programs, inseparable from the array, PowerShell is no exception. Creating and using arrays in PowerShell is an unprecedented pleasure, it is simple, easy to use too much! Oh!
1. Defining arrays
In PowerShell, all variables need not be defined, and so is the array, so this step is omitted.
2. Initializing an array
Copy Code code as follows:
$arr =1,2,3, ' A ', ' B ', ' xx ';
In the above example, Hongo initializes the array with the variable named $arr. Initializing an array in PowerShell is to assign all of the array elements-no matter what type-to it. Each array element is separated by commas (,).
After initialization, $arr this array has 6 array elements.
3, get the value of the array element
In PowerShell, the index of an array element or subscript starts at 0, which is the $arr[0]=1 in the previous example, and $arr[5]= ' xx '. $arr [5] is already the last element, if we call $arr[6], the system will not complain, just will not output any content.
4, get a part of the value of the array elements
PowerShell array, the best thing to play gets a part of the array element, and look at the example below.
Copy Code code as follows:
PS > $arr [0]
1
PS > $arr [0+3]
A
PS > $arr [0,3]
1
A
PS > $arr [0,1+3..5]
1
2
A
B
Xx
PS > $arr [-1]
Xx
PS > $arr [-2]
B
5, get the number of elements of the array
Copy Code code as follows:
6, traversing the array
Method One:
Copy Code code as follows:
foreach ($a in $arr) {$a}
foreach is very convenient for traversing a set (an array is also a collection).
Method Two:
Copy Code code as follows:
for ($i =0; $i-lt $arr. Length; $i + +) {$arr [$i]}
This is the ordinary for loop, from C to C + +, and then to Java or C #, has always been so written, we should be more familiar.
Method Three:
Copy Code code as follows:
$i = 0; while ($i-lt $arr. Length) {$arr [$i]; $i + +}
While loops are about the same as for, they are old fashioned.
7, modify the value of a single array element
Copy Code code as follows:
PS > $arr [1]=22;
PS > $arr. SetValue (22,1);
The above two statements have the same effect as assigning a value of 22 to the element (that is, the second element) labeled 1.