Showing posts with label powershell pro. Show all posts
Showing posts with label powershell pro. Show all posts

Sunday, February 20, 2011

Using Windows PowerShell as an IT Pro – Part 17

Using Windows PowerShell as an IT Pro – Part 17

In my last post I looked at some Comparison Operators. Now I will examine some more Comparison Operators.
Greater than and Less than operators
The greater than operator (-gt) returns a value of TRUE or the matches when one or more of the input values is greater than the specified pattern. The less than operator (-lt) returns a value of TRUE or the matches when one or more of the input values is less than the specified pattern. When the ‘or equals to’ operators (-ge, -le) are used, they also compare to see if the value is equal to the specified pattern.
The following examples show the effects of these operators.

8 -gt 7
CompOper05
8 -ge 8
CompOper06
"c" -lt "a"
CompOper07
"a" -le "c"
CompOper08
1, 2, 3 -le 2
CompOper09

Containment Operators
The containment operators (-contains and -notcontains) are similar to the equality operators. However, the containment operators always return a Boolean value, even when the input is a collection.
Also, unlike the equality operators, the containment operators return a value as soon as they detect the first match. The equality operators evaluate all input and then return all the matches in the collection. In a very large collection, the -contains operator returns results quicker than the equal to operator. The following examples show the effect of the -contains operator.

1, 2, 3 -contains 2
CompOper10
"PowerShell" -contains "Shell"
CompOper11
"Windows", "PowerShell" -notcontains "Shell"
CompOper12

In my next post we will finish looking at Comparison Operators.

Using Windows PowerShell as an IT Pro – Part 16

Using Windows PowerShell as an IT Pro – Part 16

In my last post I looked at Assignment Operators. Now I will examine Comparison Operators.
Comparison operators let you specify conditions for comparing values and finding values that match specified patterns. To use a comparison operator, specify the values that you want to compare together with an operator that separates these values.
By default, all comparison operators are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a "c". For example, the case-sensitive version of "-eq" is "-ceq". To make the case-insensitivity explicit, precede the operator with an "i". For example, the explicitly case-insensitive version of "-eq" is "ieq".
All comparison operators except the containment operators (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean value when the input to the operator (the value on the left side of the operator) is a single value (a scalar). When the input is a collection of values, the containment operators and the type operators return any matching values. If there are no matches in a collection, these operators do not return anything. The containment operators and type operators always return a Boolean value.
Windows PowerShell supports the following comparison operators.

Operator
Description
-eq
Equal to. Includes an identical value.
-ne
Not equal to. Includes a different value.
-gt
Greater-than.
-ge
Greater-than or equal to.
-lt
Less-than.
-le
Less-than or equal to.
-like
Match using the wildcard character (*).
-notlike
Does not match using the wildcard character (*).
-match
Matches a string using regular expressions. When the input is scalar, it populates the $Matches automatic variable.
-notmatch
Does not match a string. Uses regular expressions. When the input is scalar, it populates the $Matches automatic variable.
-contains
Containment operator. Includes an identical value that is not part of a value. Always returns a Boolean value.
-notcontains
Containment operator. Does not include an identical value. Always returns Boolean.
-replace
Replace operator. Changes the specified elements of a value.
Equality Operators
The equality operators (-eq, -ne) return a value of TRUE or matches when one or more of the input values is identical to the specified pattern. The entire pattern must match an entire value.
The following examples show the effect of the equal to operator:
"a" -eq "A"
CompOper01
"a" -ceq "A"
CompOper02
1, 2, 3 -eq 2
CompOper03
"Power" -ne "Shell"
CompOper04
In my next post we will examine more Comparison Operators.

Using Windows PowerShell as an IT Pro – Part 15

Using Windows PowerShell as an IT Pro – Part 15

In my last post I reviewed Arithmetic Operators. Now I will explore Assignment Operators.
Assignment operators assign one or more values to a variable and perform numeric operations on the values before the assignment. Windows PowerShell supports the following assignment operators.
Operator Description
= Sets the value of a variable to the specified value.
+= Increases the value of a variable by the specified value, or appends the specified value to the existing value.
-= Decreases the value of a variable by the specified value.
*= Multiplies the value of a variable by the specified value, or appends the specified value to the existing value.
/= Divides the value of a variable by the specified value.
%= Divides the value of a variable by the specified value and then assigns the remainder (modulus) to the variable.
++ Increases the value of a variable, assignable property, or array element by 1.
Decreases the value of a variable, assignable property, or array element by 1.
The assignment operator (=) assigns values to variables. If the variable already has a value, the assignment operator (=) replaces the value without warning. Since the assignment operator has been mentioned multiple times in this training, no additional details are included here.
The assignment by addition, subtraction, multiplication, and division operators all work more or less the same way. For numeric types it takes the first part of the operator (+, -, *, /) and performs the appropriate calculation and then it assigns the result. For strings, it appends the specified value to the existing value. The assignment by subtraction and division operators do not work with strings. Let’s take a closer look at several of these operators.
The assignment by addition operator (+=) either increments the value of a variable or appends the specified value to the existing value. The action depends on whether the variable has a numeric or string type and whether the variable contains a single value (a scalar) or multiple values (a collection). First, it adds, and then it assigns.
$a = 5
$a += 2
$a
Operator06
When the value of the variable is a string, the value on the right side of the operator is appended to the string.
$a = "String"
$a += ” Appended”
$a
Operator07
The assignment by subtraction operator (-=) decrements the value of a variable by the value that is specified on the right side of the operator. This operator cannot be used with string variables and it cannot be used to remove an element from a collection. First, it subtracts, and then it assigns.
$a = 5
$a -= 2
$a
Operator08
The increment operator (++) increases the value of a variable by 1. When you use the increment operator in a simple statement, no value is returned.
$a = 6
++$a
$a
Operator09
The decrement operator (–) decreases the value of a variable by 1. As with the increment operator, no value is returned when you use the operator in a simple statement. Use parentheses to return a value.
$a = 6
(–$a)
Operator10
In my next post we will examine Comparison Operators.

Using Windows PowerShell as an IT Pro – Part 14

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
Operator01
10+4/2
Operator02
(10+4)/2
Operator03
(3+3)/(1+1)
Operator04
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.

Using Windows PowerShell as an IT Pro – Part 13

Using Windows PowerShell as an IT Pro – Part 13

In my last post I looked at some basic variable types. Now I will examine arrays.
An array is a data structure for storing a collection of data elements of the same type. Basically this means that you can have a single variable that stores multiple values.
Assign multiple values to a variable to create and initialize an array. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator (=).
For example, to create an array named $a that contains the seven numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type:
$a = 20,4,11,3,1,9,60

When no data type is specified, Windows PowerShell creates each array as an object array (type: object[]). You can create a strongly typed array, that is, an array that can contain only values of a particular type, the same way you create a strongly typed variable. You specify a type, such as string[], long[], or int32[]. Precede the variable name with an array type enclosed in brackets to cast an array.
[int32[]]$ia = 1500,2230,3350,4000

Simply type the array name to display all the elements in the array. For example:
$ia

You can refer to the elements in an array by using an index, beginning at position 0. Enclose the index number in brackets. For example, to display the third element in the $a array, type:
$ia[2]

You can create arrays that are cast to any supported type in the Microsoft .NET Framework. For example, the objects that Get-Process retrieves to represent processes are of the System.Diagnostics.Process type. Enter the following command to create a strongly typed array of process objects.
[Diagnostics.Process[]]$gp = Get-Process

Then, display the contents of $gp to see a list of running processes.
$gp

In my next post we will review operators and expressions.

Using Windows PowerShell as an IT Pro – Part 12

Using Windows PowerShell as an IT Pro – Part 12

In my last post I began looking at variables. Now I will go over types and how they function.
Windows PowerShell supports a number of different types such as strings, integers, arrays, etc. You can explicitly specify a type or allow Windows PowerShell to do it dynamically, which is sometimes referred to as automatic type conversion. Type conversions are used when an object of one type is assigned a value that requires another type (such as adding a string to a number). This conversion happens automatically as long as the type was not specified manually, and it is not destructive to the original object.
For example we can assign a new value to the $Loc variable which currently has the System.Management.Automation.PathInfo type, and then use the GetType method to show its new type.
$Loc = "Test"
$Loc.GetType().FullName


Then, assign it a numeric value and check the type again.
$Loc = 3
$Loc.GetType().FullName


$Loc was made an Int32 because the value wasn’t enclosed in quotes and because the value was composed solely of digits. Had it been in quotes, it would have been interpreted as a System.String.
In both cases, Windows PowerShell determined the data type that was the most appropriate for the value of the variable. This should work for most variables but there may be situations where you want the variable type to remain as it is. Suppose you are reading values out of a file and you always want the values to be treated as strings. Some of the values, however, might contain only digits, raising the possibility that Windows PowerShell would treat them as Int32 or another numeric type, which may create problems for your script. If Windows PowerShell does not recognize the value as a string, then all the methods of the System.String class are not available (and your script might rely on one of these unavailable methods).
Manually assigning a type is simple and is done when you create it. Assigning a string to a variable essentially forces the variable to be of the System.String class. Assigning a number to a variable, on the other hand, usually results in the variable becoming an Integer (or, more specifically, an Int32, which can store a specific range of values). For example, we can create a new variable and define it as a string.
[String]$var = 5
$Var.GetType().FullName


Normally, $Var would have been an Int32, but because we defined it as a String, it makes the numeric value we assigned to it a string.
Forcibly declaring variables does have repercussions, though they are not necessarily bad. In the next example, a new variable is created, defined as an integer, and assigned a numeric value. Then, it is assigned a string value.
[Int]$Num = 4
$Num = "test"


As shown above, when we tried to assign a string value to it, an error message was displayed. Because $Num was defined as a Int32, Windows PowerShell expected to convert the string “test” into an integer value. It was unable to do this, nor was it able to change the type of $Num to String.
In my next post we continue to look at types.

Using Windows PowerShell as an IT Pro – Part 11

Using Windows PowerShell as an IT Pro – Part 11

In my last post I reviewed the Out-Gridview cmdlet. Now I will look at variables.
Windows PowerShell lets you create variables – essentially named objects – to preserve output for later use. The Windows PowerShell variables are actually mapped to underlying classes in the Microsoft® .NET Framework. In the Framework, variables are objects, meaning they can store data and also manipulate it in many ways.
Variables are always specified with the initial character $ and can include a mix of letters, numbers, symbols, or even spaces. However, if spaces are used, the variable needs to be enclosed in braces, such as: ${My Variable} = “Hello”). Variables are created by typing a valid variable name or assigning a value to it. A variable name should help you remember what it contains, using a simple, straight-forward name.
$Loc = Get-Location

Output is not displayed when this command is entered, because the output is sent to $Loc. In Windows PowerShell, displayed output is a side effect of the fact that data which is not otherwise directed always gets sent to the screen. Typing $Loc shows its value, which in this case is the current location.
$Loc

Get-Member is used to display information about the contents of variables. Get-Member enumerates the properties and methods of that object type. Piping $Loc to Get-Member shows that it is a PathInfo object, just like the output from Get-Location.
$Loc | Get-Member

There is also a default variable that can be used for certain situations. The $_ acts a placeholder for the current object. This can be used to access the properties or methods of the current object in a command. For example we can use $_ to help filter the output of the Get-Service cmdlet, displaying only services that have a status of Running.
Get-Service | where {$_.status -eq "Running"}

In my next post we continue to look at variables and types.

Using Windows PowerShell as an IT Pro – Part 10

Using Windows PowerShell as an IT Pro – Part 10

In my last post I reviewed some the format cmdlets. Now I will play with the Out-Gridview cmdlet.
Windows PowerShell 2.0 provides a few new tools that help to treat you more like a human than a machine. For example, by using the Out-Gridview cmdlet after retrieving a list of items, you can have the output is pipelined to a separate window (Graphic 24).
Get-Service | Out-Gridview


From this window, the list can be sorted by clicking the column header. However, this is output from the command, not the objects themselves, preventing any manipulation directly from this window. For example, you cannot right-click an item here to get a context menu to appear in order to stop or start a service.

The PowerShell grid also includes a rudimentary filtering function, showing only those services whose returned data includes a specified keyword. Simply type that keyword in the text box labeled Search. After entering the keyword, the grid filters out any items that do not include that keyword in at least one of the columns.

If you want to limit the filter to a specific column, type the column name followed by a colon, and then the filter string, reducing the results to four services on the computer in this example.

In my next post we get into variables and types.

Using Windows PowerShell as an IT Pro – Part 9

Using Windows PowerShell as an IT Pro – Part 9

In my last post I wrapped up the format cmdlets. Now I will take a look at the output cmdlets.
Windows PowerShell provides several cmdlets that let you control data output directly. These cmdlets share two important characteristics.
First, they generally transform data to some form of text. They do this because they output the data to system components that require text input. This means they need to represent the objects as text. Therefore, the text is formatted as you see it in the Windows PowerShell console window.
Second, these cmdlets use the Windows PowerShell verb Out because they send information out from Windows PowerShell to somewhere else. The Out-Host cmdlet is no exception: the host window display is outside of Windows PowerShell. This is important because when data is sent out of Windows PowerShell, it is actually removed. Because of this, any output cmdlets needs to be put at the end of the pipeline, otherwise the data is sent out of Windows PowerShell and any subsequent commands will have nothing to process.
The Output cmdlets are Out-Default, Out-File, Out-GridView, Out-Host, Out-Null, Out-Printer, and Out-String.
Output can be sent to a file by using the Out-File cmdlet. The following command line sends a list of services to the file C:\temp\serviceslist.txt:
Get-Service | Out-File -FilePath C:\temp\serviceslist.txt

The results of using the Out-File cmdlet may not be what you expect if you are used to traditional output redirection. You must be aware of the context in which the Out-File cmdlet operates to understand its behavior.
By default, the Out-File cmdlet creates a Unicode file. This is the best default in the long run, but it means that tools that expect ASCII files will not work correctly with the default output format. The Out-file formats file contents to look like console output, causing the output to be truncated just as it is in a console window in most circumstances.
The Out-Null cmdlet is designed to immediately discard any input it receives, which is useful for discarding unnecessary data obtained as a side-effect of running a command. When entering the following command (Graphic 22), the command results stating that the directory was created are not delivered.
New-Item -Path C:\ -Name test -Type Directory | Out-Null

The Out-Printer cmdlet routes the output to the specified printer. The Out-String cmdlet converts the objects that Windows PowerShell manages into an array of strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the stream parameter to direct Out-String to return one string at a time. This cmdlet lets you search and manipulate string output as you would in traditional shells when object manipulation is less convenient.
In my next post we will look at the Out-Gridview cmdlet.

Using Windows PowerShell as an IT Pro – Part 8

Using Windows PowerShell as an IT Pro – Part 8

In my last post I talked about the format cmdlets. Now I will continue to examine the format cmdlets.
Using the Format-Table cmdlet with no property names specified to format the output of the Get-Process command, provides exactly the same output returned without performing any formatting. The reason is that processes are usually displayed in a tabular format, as are most Windows PowerShell objects.
The displayed properties can be controlled by any of the format cmdlets by leveraging the property parameter. In this example, the format of the table displays with three specific properties.
Get-Service m* | Format-Table -Property Status, Name, ServiceType
Format04
Before I show an example of a more advanced formatting command, let’s look at some sorting. The Sort-Object cmdlet sorts objects in ascending or descending order based on the values of properties of the object.
You can specify a single property or multiple properties (for a multi-key sort) and you can select a case-sensitive or case-insensitive sort. You can also direct Sort-Object to display only the objects with a unique value for a particular property. This command displays a sort of services by status.
Get-Service m* | Sort-Object Status
Format05
You can also perform advanced formatting by combining formatting commands and adding some grouping. This command sorts the service list by status, before passing the output to the format-table command, which groups the output by status. In the displayed output the stopped and running services are grouped together, and under each status is a table containing the name and display name of each service.
Get-Service m* | Sort-Object Status | Format-Table –Group Status -Property Name, DisplayName
Format06
In my next post we will look at the Output commands.

Using Windows PowerShell as an IT Pro – Part 7

Using Windows PowerShell as an IT Pro – Part 7

In my last post I talked about how to pipe commands. Now I will talk about formatting the output of cmdlets.
Windows PowerShell has a set of cmdlets that allow you to control which properties are displayed for particular objects and where you can send the output. The names of the cmdlets begin with the verbs Format and Out. I will begin by looking at some of the Format cmdlets.
The Format cmdlets let you select one or more properties to show. The Format cmdlets are: Format-Wide, Format-List, Format-Table, and Format-Custom.
Essentially they allow you to:
Make the output from commands easier to understand
See more detailed output
See only what you want to see
Each Format cmdlet has default properties that are used if specific properties are not selected for display. Each cmdlet also uses the same parameter name, Property, to specify which properties you want to display. Because Format-Wide only shows a single property, its Property parameter only takes a single value, but the property parameters of Format-List and Format-Table accept a list of property names.
When the Get-Service command is used, it provides a basic table of services containing three columns, including column headers. This table of services provides basic information about the services.
Get-Service m*
Format01
However, we can take the output of the Get-Service command and pipe it through the Format-List command.
Get-Service m* | Format-List
Format02
Here, the output looks quite a bit different and now displays a list of services and service properties. More properties of each service are displayed in the list view. Here, for example, information about related services, what state the service is allowed to be in, and the type of service it is are displayed.
The Format-Wide command shows only a single property of the services while displaying them in two columns. You can use the Format-Custom cmdlet to perform more advanced, customized output formatting with Windows PowerShell to help you get the output you need in the format you need.
Get-Service m* | Format-Wide
Format03
In my next post we will look at some more Format commands and see how to some more advanced formatting.

Using Windows PowerShell as an IT Pro – Part 6

Using Windows PowerShell as an IT Pro – Part 6


In my last post I talked about how to create a profile and add commands to it. Now I will talk about piping commands.
One major advantage of using objects is that it makes it much easier to pipeline commands, that is, to pass the output of one command to another command as input. The cmdlet that receives an object can act directly on its properties and methods without any conversion or manipulation. Users can refer to properties and methods of the object by name, rather than calculating the position of the data in the output.
Pipelines act like a series of connected segments of pipe. Items moving along the pipeline pass through each segment. To create a pipeline in Windows PowerShell, you connect commands together with the pipe operator “|”. The output of each command is used as input to the next command.
Piping works virtually everywhere in Windows PowerShell. Although you see text on the screen, Windows PowerShell does not pipe text between commands. Instead, it pipes objects.
The notation used for pipelines is similar to that used in other shells, so at first glance, it may not be apparent that Windows PowerShell introduces something new. For example, if you use the Out-Host cmdlet to force a page-by-page display of output from another command, the output looks just like the normal text displayed on the screen, broken up into pages:
Get-ChildItem -Path C:\WINDOWS\System32 | Out-Host -Paging
Pipe01
The Out-Host -Paging command is a useful pipeline element whenever you have lengthy output that you would like to display slowly. It is especially useful if the operation is very CPU-intensive. Because processing is transferred to the Out-Host cmdlet when it has a complete page ready to display, cmdlets that precede it in the pipeline halt operation until the next page of output is available.
You will see the pipe used a lot in my future blog posts and get a better idea of how and where it can be used.
In my next post we will look at different formatting options in Windows PowerShell.