1. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
TABLE OF CONTENTS
LAB 3 #
WORKING WITH FILE AND PIPELINE PARAMETER BINDING #
EXPORTING USER INFORMATION TO A FILE #
SEND OUTPUT CONSISTING OF PIPELINE DATA #
PREDICTING PIPELINE BEHAVIOR #
Listing All the Files and Folders Within a Folder
You can get all items directly within a folder by using Get-ChildItem. Add the
optional Force parameter to display hidden or system items. For example, this
command displays the direct contents of Windows PowerShell Drive C (which is
the same as the Windows physical drive C):
Get-ChildItem -Path C: -Force
The command lists only the directly contained items, much like using
Cmd.exe's DIR command or ls in a UNIX shell. In order to show contained items,
you need to specify the -Recurse parameter as well. (This can take an extremely
long time to complete.) To list everything on the C drive:
Get-ChildItem -Path C: -Force -Recurse
Get-ChildItem can filter items with its Path, Filter, Include,
and Exclude parameters, but those are typically based only on name. You can
perform complex filtering based on other properties of items by using Where-
Object.
The following command finds all executables within the Program Files folder that
were last modified after October 1, 2005 and which are neither smaller than 1
megabyte nor larger than 10 megabytes:
PS C:Windowssystem32> Copy-Item -Path C:UsersuserDesktopa -Destination
C:UsersuserDesktopv
2. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
PS C:Windowssystem32> Get-ChildItem -Path C:UsersuserDesktopv -Force
Directory: C:UsersuserDesktopv
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/14/2020 1:01 PM a
-a---- 1/14/2020 11:39 AM 72 hh.csv
PS C:Windowssystem32>
If the destination file already exists, the copy attempt fails. To overwrite a pre-existing destination,
use the Force parameter:
PS C:Windowssystem32> Copy-Item -Path C:UsersuserDesktopa -Destination
C:UsersuserDesktopv -Force
PS C:Windowssystem32> Get-ChildItem -Path C:UsersuserDesktopv -Force
Directory: C:UsersuserDesktopv
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/14/2020 1:01 PM a
-a---- 1/14/2020 11:39 AM 72 hh.csv
Removing All Files and Folders Within a Folder
You can remove contained items using Remove-Item, but you will be prompted
to confirm the removal if the item contains anything else. For example, if you
attempt to delete the folder C:tempDeleteMe that contains other items, Windows
PowerShell prompts you for confirmation before deleting the folder:
Remove-Item -Path C:tempDeleteMe
Confirm
The item at C:tempDeleteMe has children and the -recurse parameter was not
specified. If you continue, all children will be removed with the item. Are you sure
you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):
3. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
If you do not want to be prompted for each contained item, specify
the Recurse parameter:
The PowerShell Pipeline
Pipelines are arguably the most valuable concept used in command-line interfaces.
When used properly, pipelines reduce the effort of using complex commands and
make it easier to see the flow of work for the commands. Each command in a
pipeline (called a pipeline element) passes its output to the next command in the
pipeline, item-by-item. Commands don't have to handle more than one item at a
time. The result is reduced resource consumption and the ability to begin getting
the output immediately.
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:WINDOWSSystem32 | Out-Host -Paging
Paging also reduces CPU utilization because processing transfers to the Out-
Host cmdlet when it has a complete page ready to display. The cmdlets that
precede it in the pipeline pause execution until the next page of output is
available.
You can see how piping impacts CPU and memory usage in the Windows Task
Manager by comparing the following commands:
Get-ChildItem C:Windows -Recurse
Get-ChildItem C:Windows -Recurse | Out-Host -Paging
Objects in the pipeline
4. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
When you run a cmdlet in PowerShell, you see text output because it is necessary
to represent objects as text in a console window. The text output may not display
all of the properties of the object being output.
For example, consider the Get-Location cmdlet. If you run Get-Location while your
current location is the root of the C drive, you see the following output:
PS> Get-Location
Path
----
C:
The text output is a summary of information, not a complete representation of
the object returned by Get-Location. The heading in the output is added by the
process that formats the data for onscreen display.
When you pipe the output to the Get-Member cmdlet you get information about
the object returned by Get-Location.
Get-Location | Get-Member
The first command uses the Get-Process cmdlet to get an object representing the
Notepad process. It uses a pipeline operator (|) to send the process object to
the Stop-Process cmdlet, which stops the Notepad process. Notice that the Stop-
Process command doesn't have a Name or ID parameter to specify the process,
because the specified process is submitted through the pipeline.
This pipeline example gets the text files in the current directory, selects only the
files that are more than 10,000 bytes long, sorts them by length, and displays the
name and length of each file in a table.
Get-ChildItem -Path *.txt |
Where-Object {$_.length -gt 10000} |
Sort-Object -Property length |
Format-Table -Property name, length
5. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
How pipelines work
This section explains how input objects are bound to cmdlet parameters and
processed during pipeline execution.
Accepts pipeline input
To support pipelining, the receiving cmdlet must have a parameter that accepts
pipeline input. Use the Get-Help command with the Full or Parameter options to
determine which parameters of a cmdlet accept pipeline input.
For example, to determine which of the parameters of the Start-Service cmdlet
accepts pipeline input, type:
Get-Help Start-Service -Full
Or
Get-Help Start-Service -Parameter *
The help for the Start-Service cmdlet shows that only
the InputObject and Name parameters accept pipeline input.
When you send objects through the pipeline to Start-Service, PowerShell attempts
to associate the objects with the InputObject and Name parameters.
Methods of accepting pipeline input
Cmdlets parameters can accept pipeline input in one of two different ways:
• ByValue: The parameter accepts values that match the expected .NET type or
that can be converted to that type.
For example, the Name parameter of Start-Service accepts pipeline input by
value. It can accept string objects or objects that can be converted to strings.
• ByPropertyName: The parameter accepts input only when the input object
has a property of the same name as the parameter.
For example, the Name parameter of Start-Service can accept objects that
have a Name property. To list the properties of an object, pipe it to Get-
Member.
6. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
Some parameters can accept objects by both value or property name, making it
easier to take input from the pipeline.
Parameter binding
When you pipe objects from one command to another command, PowerShell
attempts to associate the piped objects with a parameter of the receiving cmdlet.
PowerShell's parameter binding component associates the input objects with
cmdlet parameters according to the following criteria:
• The parameter must accept input from a pipeline.
• The parameter must accept the type of object being sent or a type that can be converted to
the expected type.
• The parameter wasn't used in the command.
For example, the Start-Service cmdlet has many parameters, but only two of
them, Name and InputObject accept pipeline input. The Name parameter takes
strings and the InputObject parameter takes service objects. Therefore, you can
pipe strings, service objects, and objects with properties that can be converted to
string or service objects.
PowerShell manages parameter binding as efficiently as possible. You can't
suggest or force the PowerShell to bind to a specific parameter. The command fails
if PowerShell can't bind the piped objects.
For more information about troubleshooting binding errors, see Investigating
Pipeline Errors later in this article.
One-at-a-time processing
Piping objects to a command is much like using a parameter of the command to
submit the objects. Let's look at a pipeline example. In this example, we use a
pipeline to display a table of service objects.
Get-Service | Format-Table -Property Name, DependentServices
Functionally, this is like using the InputObject parameter of Format-Table to
submit the object collection.
For example, we can save the collection of services to a variable that is passed using
the InputObject parameter.
7. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
$services = Get-Service
Format-Table -InputObject $services -Property Name, DependentServices
Or we can embed the command in the InputObject parameter.
Format-Table -InputObject (Get-Service) -Property Name, DependentServices
However, there's an important difference. When you pipe multiple objects to a
command, PowerShell sends the objects to the command one at a time. When you
use a command parameter, the objects are sent as a single array object. This minor
difference has significant consequences.
When executing a pipeline, PowerShell automatically enumerates any type that
implements the IEnumerable interface and sends the members through the pipeline
one at a time. The exception is [hashtable], which requires a call to
the GetEnumerator() method.
In the following examples, an array and a hashtable are piped to the Measure-
Object cmdlet to count the number of objects received from the pipeline. The array
has multiple members, and the hashtable has multiple key-value pairs. Only the
array is enumerated one at a time.
PS C:Windowssystem32> @(1,2,3) | Measure-Object
Count : 3
Average :
Sum :
Maximum :
Minimum :
Property :
PS C:Windowssystem32> @{"One"=1;"Two"=2} | Measure-Object
Count : 1
Average :
Sum :
Maximum :
Minimum :
Property :
Similarly, if you pipe multiple process objects from the Get-Process cmdlet to
the Get-Member cmdlet, PowerShell sends each process object, one at a time, to Get-
Member. Get-Member displays the .NET class (type) of the process objects, and their
properties and methods.
Get-Process | Get-Member
8. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
However, if you use the InputObject parameter of Get-Member, then Get-
Member receives an array of System.Diagnostics.Process objects as a single unit. It
displays the properties of an array of objects. (Note the array symbol ([]) after
the System.Object type name.)
Get-Member -InputObject (Get-Process)
TypeName: System.Object[]
Name MemberType Definition
---- ---------- ----------
Count AliasProperty Count = Length
Add Method int IList.Add(System.Object value)
Address Method System.Object&, mscorlib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089 Address(int )
Clear Method void IList.Clear()
Clone Method System.Object Clone(), System.Object
ICloneable.Clone()
CompareTo Method int
IStructuralComparable.CompareTo(System.Object other,
System.Collections.IComparer comparer)
Contains Method bool IList.Contains(System.Object value)
CopyTo Method void CopyTo(array array, int index), void
CopyTo(array array, long index), void ICollection.CopyTo(array array, int
index)
Equals Method bool Equals(System.Object obj), bool
IStructuralEquatable.Equals(System.Object other,
System.Collections.IEqualityComparer comparer)
This result might not be what you intended. But after you understand it, you can
use it. For example, all array objects have a Count property. You can use that to
count the number of processes running on the computer.
For example,
PS C:Windowssystem32> (Get-Process).count
64
About If
SHORT DESCRIPTION
Describes a language command you can use to run statement lists based on the
results of one or more conditional tests.
LONG DESCRIPTION
You can use the If statement to run code blocks if a specified conditional test
evaluates to true. You can also specify one or more additional conditional tests to
9. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
run if all the prior tests evaluate to false. Finally, you can specify an additional code
block that is run if no other prior conditional test evaluates to true.
Syntax
The following example shows the If statement syntax:
PowerShell
if (<test1>)
{<statement list 1>}
[elseif (<test2>)
{<statement list 2>}]
[else
{<statement list 3>}]
When you run an If statement, PowerShell evaluates the <test1> conditional
expression as true or false. If <test1> is true, <statement list 1> runs, and
PowerShell exits the If statement. If <test1> is false, PowerShell evaluates the
condition specified by the <test2> conditional statement.
If <test2> is true, <statement list 2> runs, and PowerShell exits the If statement. If
both <test1> and <test2> evaluate to false,
the <statement list 3> code block runs, and
PowerShell exits the If statement.
You can use multiple Elseif statements to
chain a series of conditional tests. So, that
each test is run only if all the previous tests
are false. If you need to create an If
statement that contains many Elseif
statements, consider using a Switch
statement instead.
Examples:
The simplest If statement contains a single
command and does not contain any Elseif
statements or any Else statements. The following example shows the simplest form
of the If statement:
10. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
$x = 30
if($x -le 20){
write-host("This is if statement")
}else {
write-host("This is else statement")
}
if ($a -gt 2) { Write-Host "The value $a is greater than 2."}
In this example, if the $a variable is greater than 2, the condition evaluates to true,
and the statement list runs. However, if $a is less than or equal to 2 or is not an
existing variable, the If statement does not display a message.
By adding an Else statement, a message is displayed when $a is less than or equal
to 2. As the next example shows:
The if...elseif...else Statement
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...elseif statement. When using if,
elseif, else statements there are a few points to keep in mind. An if can have zero
or one else's and it must come after any elseif's. An if can have zero to many elseif's
and they must come before the else. Once an else if succeeds, none of the
remaining elseif's or else's will be tested.
Syntax: Following is the syntax of an if...else statement −
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}elseif(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}elseif(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}
$x = 30
if($x -eq 10){
write-host("Value of X is 10")
} elseif($x -eq 20){
write-host("Value of X is 20")
} elseif($x -eq 30){
11. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
write-host("Value of X is 30")
} else {
write-host("This is else statement")
}
This will produce the following result −
Output
Value of X is 30
About Comparison Operators
Short description
Describes the operators that compare values in PowerShell.
Long description
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.
PowerShell includes the following comparison operators:
Type Operators Description
Equality -eq equals
-ne not equals
-gt greater than
-ge greater than or equal
-lt less than
-le less than or equal
Matching -like Returns true when string matches wildcard
12. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
Type Operators Description
pattern
-notlike Returns true when string does not match
wildcard pattern
-match Returns true when string matches regex
pattern; $matches contains matching strings
-notmatch Returns true when string does not match
regex pattern; $matches contains matching
strings
Containment -contains Returns true when reference value contained
in a collection
-notcontains Returns true when reference value not
contained in a collection
-in Returns true when test value contained in a
collection
-notin Returns true when test value not contained
in a collection
Replacement -replace Replaces a string pattern
Type -is Returns true if both objects are the same
type
13. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
Type Operators Description
-isnot Returns true if the objects are not the same
type
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.
When the input to an operator is a scalar value, comparison operators return a
Boolean value. When the input is a collection of values, the comparison operators
return any matching values. If there are no matches in a collection, comparison
operators do not return anything.
The exceptions are the containment operators (-contains, -notcontains), the In
operators (-in, -notin), and the type operators (-is, -isnot), which always return a
Boolean value.
Equality Operators
The equality operators (-eq, -ne) return a value of TRUE or the matches when one
or more of the input values is identical to the specified pattern. The entire pattern
must match an entire value.
Example:
-eq
Description: Equal to. Includes an identical value.
C:PS> 2 -eq 2
True
C:PS> 2 -eq 3
False
C:PS> 1,2,3 -eq 2
2
PS> "abc" -eq "abc"
True
15. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
8
9
-lt
Description: Less-than.
Example:
PS> 8 -lt 6
False
PS> 7, 8, 9 -lt 8
7
-le
Description: Less-than or equal to.
Example:
PS> 6 -le 8
True
PS> 7, 8, 9 -le 8
7
8
Matching Operators
The like operators (-like and -notlike) find elements that match or do not match
a specified pattern using wildcard expressions.
The syntax is:
<string[]> -like <wildcard-expression>
<string[]> -notlike <wildcard-expression>
16. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
-like
Description: Match using the wildcard character (*).
Example:
PS> "PowerShell" -like "*shell"
True
PS> "PowerShell", "Server" -like "*shell"
PowerShell
-notlike
Description: Does not match using the wildcard character (*).
Example:
PS> "PowerShell" -notlike "*shell"
False
PS> "PowerShell", "Server" -notlike "*shell"
Server
-match
Description: Matches a string using regular expressions. When the input is scalar,
it populates the $Matches automatic variable.
The match operators search only in strings. They cannot search in arrays of
integers or other objects.
If the input is a collection, the -match and -notmatch operators return the matching
members of that collection, but the operator does not populate
the $Matches variable.
For example, the following command submits a collection of strings to the -
match operator. The -match operator returns the items in the collection that match.
It does not populate the $Matches automatic variable.
PS> "Sunday", "Monday", "Tuesday" -match "sun"
Sunday
17. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
PS> $Matches
In contrast, the following command submits a single string to the -match operator.
The -match operator returns a Boolean value and populates the $Matches automatic
variable. The $Matches automatic variable is a Hashtable. If no grouping or
capturing is used, only one key is populated. The 0 key represents all text that was
matched. For more information about grouping and capturing using regular
expressions, see about_Regular_Expressions.
PS> "Sunday" -match "sun"
True
PS> $Matches
Name Value
---- -----
0 Sun
It is important to note that the $Matches hashtable will only contain the first
occurrence of any matching pattern.
PS> "Banana" -match "na"
True
PS> $Matches
Name Value
---- -----
0 na
About Switch
SHORT DESCRIPTION
Explains how to use a switch to handle multiple If statements.
LONG DESCRIPTION
To check a condition in a script or function, use an If statement. The If statement
can check many types of conditions, including the value of variables and the
properties of objects.
18. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
To check multiple conditions, use a Switch statement. The Switch statement is
equivalent to a series of If statements, but it is simpler. The Switch statement lists
each condition and an optional action. If a condition obtains, the action is
performed.
The Switch statement also uses the $switch automatic variable. For more
information, see about_Automatic_Variables.
A basic Switch statement has the following format:
Switch (<test-value>)
{
<condition> {<action>}
<condition> {<action>}
}
For example, the following Switch statement compares the test value, 3, to each of
the conditions. When the test value matches the condition, the action is performed.
switch (3)
{
1 {"It is one."}
2 {"It is two."}
3 {"It is three."}
4 {"It is four."}
}
switch (4, 2)
{
1 {"It is one."; Break}
2 {"It is two." ; Break }
3 {"It is three." ; Break }
4 {"It is four." ; Break }
3 {"Three again."}
}
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
case.
Syntax
The syntax of enhanced for loop is −
19. Advance Configuration Management, Windows PowerShell Hitesh Mohapatra
switch(<test-value>) {
<condition> {<action>}
break; // optional
<condition> {<action>}
break; // optional
<condition> {<action>}
break; // optional
}
The following rules apply to a switch statement −
• The variable used in a switch statement can only be any object or an array of objects.
• You can have any number of case statements within a switch. Each case is followed
by optional action to be performed.
• The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.