Tutorial 08 Powershell Cmdlet
Tutorial 08 Powershell Cmdlet
Features
Cmdlets − Cmdlets perform common system administration
tasks, for example managing the registry, services, processes,
event logs, and using Windows Management Instrumentation
(WMI).
Task oriented − PowerShell scripting language is task based and
provide supports for existing scripts and command-line tools.
Consistent design − As cmdlets and system data stores use
common syntax and have common naming conventions, data
sharing is easy. The output from one cmdlet can be pipelined
to another cmdlet without any manipulation.
Simple to Use − Simplified, command-based navigation lets
users navigate the registry and other data stores similar to the
file system navigation.
Object based − PowerShell possesses powerful object
manipulation capabilities. Objects can be sent to other tools or
databases directly.
Extensible interface. − PowerShell is customizable as independent
software vendors and enterprise developers can build custom
tools and utilities using PowerShell to administer their
software.
Creating Folders
New-Item cmdlet is used to create a directory by
passing the path using -Path as path of the directory and
-ItemType as Directory.
Example Script to show how to create folder(s) using PowerShell scripts.
New-Item -Path 'D:\temp\Test Folder' -ItemType
1 Directory
Directory: D:\temp
Creating Files
New-Item cmdlet is used to create a file by passing the
path using -Path as path of the file and -ItemType as
File.
Example Script to show how to create file(s) using PowerShell scripts.
New-Item -Path 'D:\temp\Test Folder\Test
2 File.txt' -ItemType File
Directory: D:\temp
3 Copying Folders
Copy-Item cmdlet is used to copy a directory by passing
the path of the directory to be copied and destination
path where the folder is to be copied.
Example Script to show how to copy file(s) using PowerShell scripts.
Copying Files
Copy-Item cmdlet is used to copy a file by passing the
path of the file to be copied and destination path where
the file is to be copied.
Example Script to show how to create file(s) using PowerShell scripts.
Copy-Item 'D:\temp\Test Folder\Test File.txt'
4 'D:\temp\Test Folder1\Test File1.txt'
Deleting Folders
Remove-Item cmdlet is used to delete a directory by
passing the path of the directory to be deleted.
5 Example Script to show how to delete folder(s) using PowerShell scripts.
Remove-Item 'D:\temp\Test Folder1'
Deleting Files
Remove-Item cmdlet is used to delete a file by passing
6 the path of the file to be deleted.
Example Script to show how to delete file(s) using PowerShell scripts.
Remove-Item 'D:\temp\Test Folder\test.txt'
Moving Folders
Move-Item cmdlet is used to move a directory by
passing the path of the directory to be moved and
7
destination path where the folder is to be moved.
Example Script to show how to move file(s) using PowerShell scripts.
Move-Item D:\temp\Test D:\temp\Test1
8 Moving Files
Move-Item cmdlet is used to move a file by passing the
path of the file to be moved and destination path where
the file is to be moved.
Example Script to show how to move file(s) using PowerShell scripts.
Move-Item D:\temp\Test\Test.txt D:\temp\Test1
Rename Folders
Rename-Item cmdlet is used to rename a folder by passing
9 the path of the folder to be renamed and target name.
Example Script to show how to rename folder(s) using PowerShell scripts.
Rename-Item "D:\temp\Test Test1"
Rename Files
Rename-Item cmdlet is used to rename a File by
passing the path of the file to be renamed and target
10
name.
Example Script to show how to rename file(s) using PowerShell scripts.
Rename-Item D:\temp\Test\test.txt test1.txt
Retrieving Item
Get-Content cmdlet is used to retrieve content of a file
as an array.
Example Script to show how to retrieve item(s) using PowerShell scripts.
Get-Content D:\temp\Test\test.txt
11
Get-Content D:\temp\test\test.txt
;This is a test file.
(Get-Content D:\temp\test\test.txt).length
20
Variables
$location = Get-Location
Using variable
$location
Output
Path
----
D:\test
Getting information of variable
Get-Member cmdlet can tell the type of variable being used. See the
example below.
$location | Get-Member
Output
TypeName: System.Management.Automation.PathInfo
Operator Description
$NESTEDPROMPTLEVE
Represents the current prompt level.
L
Represents the full path and file name of the script that is
$PSCOMMANDPATH
being run.
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Redirectional Operators
Spilt and Join Operators
Type Operators
Unary Operators
The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the
same way that they are used in algebra. The following table lists the
arithmetic operators
Operator Description Example
eq (equals) Compares two values to be equal or not. A -eq B will give false
ne (not equals) Compares two values to be not equal. A -ne B will give true
> $c -= $a
> $c
30
AND (logical Called Logical AND operator. If both the (A -AND B) is false
and) operands are non-zero, then the condition
becomes true.
Miscellaneous Operators
Following are various important operators supported by PowerShell
language
Operator Description Example
Example
> $location = Get-Location
> $location -is 'System.Management.Automation.PathInfo'
True
> $location -isNot
'System.Management.Automation.PathInfo'
True
> $i = 1
> $i++
> $i
2
Powershell - Looping
There may be a situation when you need to execute a block of code
several number of times. In general, statements are executed
sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Sr.No
Loop & Description
.
1 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
> $array = @("item1", "item2", "item3")
> for($i = 0; $i -lt $array.length; $i++)
{ $array[$i] }
item1
item2
item3
forEach loop
Enhanced for loop. This is mainly used to traverse collection of elements
including arrays.
> $array = @("item1", "item2", "item3")
> foreach ($element in $array) { $element }
item1
2 item2
item3
> $array | foreach { $_ }
item1
item2
item3
while loop
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
> $array = @("item1", "item2", "item3")
$counter = 0;
4 do...while loop
Like a while statement, except that it tests the condition at the end of the loop
body.
> $array = @("item1", "item2", "item3")
$counter = 0;
do {
$array[$counter]
$counter += 1
} while($counter -lt $array.length)
item1
item2
item3
Powershell - Conditions
Decision making structures have one or more conditions to be
evaluated or tested by the program, along with a statement or
statements that are to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the
condition is determined to be false.
Sr.No
Statement & Description
.
if statement
1 An if statement consists of a boolean expression followed by one or more
statements.
2 if...else statement
An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
Syntax
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
Example
$x = 30
nested if statement
You can use one if or elseif statement inside another if or elseif statement(s).
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}
Example
$x = 30
3
$y = 10
4 switch statement
A switch statement allows a variable to be tested for equality against a list of
values.
Syntax
switch(<test-value>) {
<condition> {<action>}
break; // optional
<condition> {<action>}
break; // optional
<condition> {<action>}
break; // optional
}
Example 1
switch(3){
1 {"One"}
2 {"Two"}
3 {"Three"}
4 {"Four"}
3 {"Three Again"}
}
Output
Three
Three Again
Example 2
switch(3){
1 {"One"}
2 {"Two"}
3 {"Three"; break }
4 {"Four"}
3 {"Three Again"}
}
Output
Three
Example 3
switch(4,2){
1 {"One"}
2 {"Two"}
3 {"Three"; break }
4 {"Four"}
3 {"Three Again"}
}
Output
Four
Two
Powershell - Array
PowerShell provides a data structure, the array, which stores a
fixed-size sequential collection of elements of the any type. An array
is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables or objects.
Syntax
$A = 1, 2, 3, 4
or
$A = 1..4
Note − By default type of objects of array is System.Object.
GetType() method returns the type of the array. Type can be
passed.
Example
[int32[]]$intA = 1500,2230,3350,4000
$A = 1, 2, 3, 4
$A.getType()
Output
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
The array elements are accessed through the index. Array indices
are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Example
Processing Arrays
When processing array elements, we often use either for loop
or foreach loop because all of the elements in an array are of the
same type and the size of the array is known.
Example
write-host("print subList")
$subList
write-host("Assign values")
$myList[1] = 10
$myList
Output
Print all the array elements
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
Get the length of array
10
Get Second element of array
4.5
Get partial array
print subList
4.5
3.3
13.2
using for loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using forEach Loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using while Loop
5.6
4.5
3.3
13.2
Assign values
5.6
10
3.3
13.2
4
34.33
34
45.45
99.993
11123
The Arrays Methods Examples
$myList = @(0..4)
write-host("Print array")
$myList
$myList = @(0..4)
write-host("Assign values")
$myList[1] = 10
$myList
Output
Clear array
Print array
0
1
2
3
4
Assign values
0
10
2
3
4