变量是任何类型编码(any type of coding)中最基本的数据结构。但是对于大多数目的来说,单个变量是不够的,尤其是在处理更复杂的算法时。
这就是数组的用武之地。无论是 C++ 还是Python,数组都以某种形式存在于每种编程语言中。但是Windows PowerShell呢?PowerShell数组如何工作?你如何使用它们?它们的语法是什么?让我们来了解一下。
PowerShell 阵列 101
简单(Simply)来说,数组就是变量的结构化集合。这个想法是通过将相关变量折叠成一个编号的集合来消除跟踪数十个名称的麻烦。
在PowerShell中,您可以通过将 $ 符号添加到变量名称来创建变量。例如:
$prime = 13
该变量可以包含任何数据类型,从数字到字符串。您只需要使用双引号或单引号来指定字符串。
$name = “Levin”
现在要创建一个新数组,只需将多个值分配给同一个变量,用逗号分隔。像这样:
$week = “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”
有些人喜欢将变量显式转换为数组以避免混淆,尽管这不是必需的。为此,请将值放入以 @ 符号开头的括号中。
$week = @(“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”)
当试图将其他命令的输出放入数组时,这通常会派上用场,因为您无法以正确的格式手动编写它们。
创建一个数组
我们已经看到了创建数组的最常用方法。但视情况而定,还有其他可能更合适的方式。例如,如果要创建一个包含数字范围的数组,可以使用范围运算符:
$digits = (0..9)
这将创建一个包含从零到九的所有十位数字的数组。您还可以初始化一个空数组,以防您以后只想要一个存储值的地方。
$values = @()
多个(Multiple)数组甚至可以相互嵌套,尽管这种用法会很快变得混乱。
$coordinates = @(
(5, 10, 23),
(11, 7, 16)
)
默认情况下,数组可以存储任何变量类型,可以是数字、字符串或两者的混合。但是,如果您想限制放入其中的值,您可以显式定义一个类型。例如:
[int[]] $numbers = 2,3,4,5
这样,数组只能保存整数。尝试为其分配任何其他类型的值将返回错误。这对于防止专门使用数值的数组出现简单错误很有用,因为将字符串输入到要在计算中使用的变量中会产生问题。
访问数组
到目前为止,我们已经看到了多种创建包含各种类型数据的数组的方法。但是您如何访问这些数据呢?
PowerShell数组使用与其他编程语言相同的格式。每个数组变量都可以通过其索引号访问。例如:
$var = $numbers[5]
这将复制$var变量中$numbers数组的索引 5 中存储的值。请注意,数组索引从 0 开始计数,因此第一项访问为零。
如果我们要输出这个,例如:
“$days[2]”
我们将得到星期三,而不是星期二。
您也可以使用相同的方法来修改这些值。例如,以下命令会将数组的第二个元素更改为零:
$numbers[1] = 0
您还可以向现有数组添加更多元素,而不是像算术表达式一样添加它们来更改当前条目的值。
$names += “Johny”
此方法也可用于一次添加多个条目,甚至是整个数组。
$names += “Charlie, Liam, Teresa”
$names += $surnames
逗号分隔的方法也适用于访问多个数组元素。例如,输入 this 会将$days的前五个元素存储在$weekdays中。
$weekdays = $days[0,1,2,3,4]
遍历数组
手动访问数组的特定元素很好,但如果您想对数组的全部内容执行操作,它可能会变得乏味。更优雅的方法是使用 For 循环。
for 循环可以系统地遍历数组的所有元素,根据指令处理每个值。这是构建这样一个循环的方法:
For ($i = 0 ; $i -lt $days.Length ; $i++){
$days[$i]}
array.Length 函数返回数组的大小,基本上就是其中元素的数量。这可以插入到 For 循环的测试表达式参数中,以全面迭代所有元素。
Foreach循环和Foreach -object 循环可以使用更精简的PowerShell脚本执行相同的操作。
Foreach ($day in $days){
$day}
这样可以节省您确定数组大小的工作,而将详细信息留给PowerShell处理。
什么时候应该使用PowerShell 数组(PowerShell Arrays)
复杂脚本中最大的错误来源是错误引用的变量。这是因为存在大量唯一命名的变量,这使得很难记住它们的用途。
解决此问题的最简单方法是广泛使用数组。所有以某种方式相关的变量都可以分配给单个数组并通过它们的索引号访问。
Microsoft PowerShell 的(Microsoft PowerShell’s)主要用例是自动化,而阵列在其中发挥着关键作用。PowerShell cmdlet返回的对象可以存储到数组中并进行迭代。这允许自动执行顺序任务,大大简化了系统管理。
PowerShell Arrays: How to Create and Use Them
Variables arе the most bаsic data strυcture in any type of coding. But single variables are hardly sufficient for most purposes, especially when dealing with more complex algorithms.
That’s where arrays come in. Be it C++ or Python, arrays are present in every programming language in some form. But what about Windows PowerShell? How do PowerShell arrays work? How do you use them? What is their syntax? Let’s find out.
PowerShell Arrays 101
Simply speaking, an array is just a structured collection of variables. The idea is to eliminate the hassle of keeping track of dozens of names by collapsing related variables into a numbered set.
In PowerShell, you can create a variable by prepending the $ symbol to a variable name. For example:
$prime = 13
The variable can contain any data type, from numbers to strings. You just need to use double or single quotes to specify a string.
$name = “Levin”
Now to create a new array, simply assign multiple values to the same variable, separated by commas. Like this:
$week = “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”
Some people prefer to explicitly cast a variable into an array to avoid confusion, though that isn’t necessary. To do this, put the values into parentheses prefaced with the @ symbol.
$week = @(“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”)
This usually comes in handy when trying to put the output of other commands into an array, where you cannot manually write them in the correct format.
Creating an Array
We’ve already seen the most common method of creating an array. But depending on the situation, there are other ways that might be more suitable. For example, if you want to create an array that contains a range of numbers, you can use the range operator:
$digits = (0..9)
This will create an array of all the ten digits from zero to nine. You can also initialize an empty array, in case you just want a place to store values later.
$values = @()
Multiple arrays can even be nested into one another, though this type of usage can get confusing very fast.
$coordinates = @(
(5, 10, 23),
(11, 7, 16)
)
By default an array can store any variable type, be it numbers, strings, or a mix of both. But you can explicitly define a type in case you want to limit the values put in it. For example:
[int[]] $numbers = 2,3,4,5
This way, the array can only hold integers. Attempting to assign any other type of value to it will return an error. This can be useful to prevent simple errors for arrays exclusively working with numeric values, since entering a string into a variable to be used in calculations will create issues.
Accessing Arrays
So far we have seen multiple methods for creating arrays containing various types of data. But how do you go about accessing this data?
PowerShell arrays use the same format used by other programming languages. Each array variable can be accessed by its index number. For example:
$var = $numbers[5]
This will copy the value stored in the index five of the $numbers array in the $var variable. Note that array indices start counting from 0, so the first item is accessed with zero.
If we were to output this, for example:
“$days[2]”
We will get Wednesday, not Tuesday.
You can use this same method to modify these values as well. For example, the following command will change the second element of the array to zero:
$numbers[1] = 0
You can also add more elements to an existing array instead of changing the values of current entries just by adding them like an arithmetic expression.
$names += “Johny”
This method can be used to add multiple entries at once too, or even entire arrays.
$names += “Charlie, Liam, Teresa”
$names += $surnames
The comma-separated method holds for accessing multiple array elements too. Entering this, for example, stores the first five elements of $days in $weekdays.
$weekdays = $days[0,1,2,3,4]
Iterating Through Arrays
Manually accessing particular elements of an array is well and good, but if you want to perform actions on the entire contents of an array, it can get tedious. A more elegant approach is to use a For loop.
For loops can systematically go through all the elements of an array, processing each value according to instructions. This is how you can construct such a loop:
For ($i = 0 ; $i -lt $days.Length ; $i++)
{
$days[$i]
}
The array.Length function returns the size of the array, which is basically the number of elements in it. This can be plugged into a For loop’s test expression parameter to comprehensively iterate over all the elements.
The Foreach loop and the Foreach-object loop can do the same with an even leaner PowerShell script.
Foreach ($day in $days)
{
$day
}
This saves you the effort of determining the array’s size, leaving the details for PowerShell to handle.
When Should You Use PowerShell Arrays
The biggest source of bugs in a complex script is incorrectly referenced variables. This happens due to the presence of a large number of uniquely named variables, which makes it difficult to remember their purpose.
The simplest fix for this issue is to use arrays extensively. All variables related in some manner can be assigned to a single array and accessed through their index numbers.
Microsoft PowerShell’s prime use case is automation, and arrays play a pivotal role in that. The objects returned by PowerShell cmdlets can be stored into arrays and iterated over. This allows sequential tasks to be performed automatically, greatly simplifying system administration.