Using Windows PowerShell as an IT Pro – Part 14
In my last post I reviewed arrays. Now I will explore Operators.An operator is a language element that can be used in a command or expression to perform an operation. Windows PowerShell supports several types of operators to help you manipulate values. First, let’s look at Arithmetic operators.
Arithmetic operators calculate numeric values. Arithmetic operators are used to add, subtract, multiply, and divide values, and to calculate the remainder (modulus) of a division operation.
In addition, the addition operator (+) and multiplication operator (*) also operate on strings, arrays, and hash tables. The addition operator concatenates the input. The multiplication operator returns multiple copies of the input. You can even mix object types in an arithmetic statement. The method used to evaluate the statement is determined by the type of the leftmost object in the expression.
Windows PowerShell supports the following arithmetic operators:
Operator | Description | Example |
+ | Adds integers; concatenates strings, arrays, and hash tables. | 6+2 “file” + “name” |
- | Subtracts one value from another value. | 6-2 (get-date).date – 1 |
- | Makes a number a negative number. | -6+2 -4 |
* | Multiplies integers; copies strings and arrays the specified number of times. | 6*2 “w” * 3 |
/ | Divides two values. | 6/2 |
% | Returns the remainder of a division operation. | 7%2 |
Windows PowerShell processes arithmetic operators in the following order:
· Parentheses ()
· – (for a negative number)
· *, /, %
· +, – (for subtraction)
Windows PowerShell processes the expressions from left to right according to the precedence rules. The following examples show the effect of the precedence rules:
3+6/3*4
10+4/2
(10+4)/2
(3+3)/(1+1)
You can also do this with non-numeric types. Numbers, strings, arrays, and hash tables can be added; numbers, strings, and arrays can be multiplied. However, you cannot multiply hash tables.
When adding strings, arrays, or hash tables, the elements are concatenated. When you concatenate collections, such as arrays or hash tables, a new object is created that contains the objects from both collections. If you try to concatenate hash tables that have the same key, the operation fails.
For example, the following commands creates two strings and then adds them:
$a = "1"
$b = "A"
$a + $b
In my next post we will examine assignment operators.
No comments:
Post a Comment