0% found this document useful (0 votes)
67 views82 pages

Day 5

This section introduces PowerShell and discusses cmdlets. It covers installing Windows VMs, the Cyber Aces program modules, and finding cmdlets and help information. Cmdlets allow running commands and interacting with Windows objects in a standardized way.

Uploaded by

poorvaja.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views82 pages

Day 5

This section introduces PowerShell and discusses cmdlets. It covers installing Windows VMs, the Cyber Aces program modules, and finding cmdlets and help information. Cmdlets allow running commands and interacting with Windows objects in a standardized way.

Uploaded by

poorvaja.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Welcome to Cyber Aces, Module 3!

This module provides an introduction to the


latest shell for Windows, PowerShell.
This training material was originally developed to help students, teachers, and
mentors prepare for the Cyber Aces Online Competition. This module focuses on the
basics of what an operating systems is as well as the two predominant OS's, Windows
and Linux. In this session we will provide a walkthrough of the installation a Windows
VM using VMware Fusion (MacOS) and VMware Player (Windows & Linux). These
sessions include hands-on labs, but before we begin those labs we need to install the
operating systems used in those labs. We will be using VMware to virtualize these
operating systems. You can use other virtualization technologies if you like, but
instruction for their setup and use are not included in this training.
The three modules of Cyber Aces Online are Operating Systems, Networking, and
System Administration.
For more information about the Cyber Aces program, please visit the Cyber Aces
website at https://CyberAces.org/.
Is this section, you will be introduced to PowerShell and some basic syntax.
Originally codenamed Monad (or Microsoft Shell or MSH), it was designed as a new
approach to managing Windows systems via the command line. PowerShell was
originally a separate download for Windows XP, Vista, Windows Server 2003, and
later for Window Server 2008 (R1), but it is not supported on Windows 2000 or older.
PowerShell version 2.0 was integrated into Windows 7 and was released at the same
time as Windows 7. Windows Server 2008R2 also came with PowerShell v2.0
installed. Separate installs were made available for previous versions of Windows.
The Windows 10 family includes PowerShell v5.
Prior to PowerShell, all major shells used text as input and output. As we'll see, the
use of objects allows structured data to be used as input and output which allows for
simpler manipulation of data via the command line.
PowerShell uses cmdlets (pronounced command-lets) to accomplish tasks and are
very similar to commands used by other shells and operating systems. The cmdlets
often expose more options than are available via the GUI (Graphical User Interface)
and are generally the recommended approach for adjusting advanced features of
many server packages that support PowerShell.
Read more about PowerShell:
http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx
https://en.wikipedia.org/wiki/Windows_PowerShell
PowerShell uses a verb-noun pair for cmdlet names. For example, Get-Date would
"get" the current "date." The verbs are standardized by Microsoft
(http://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx) to make
memorization easier and to ensure consistent use of names. This standard ensures
that cmdlet developers all use the verb "Add", instead of a seemingly random
assortment of "Append", "Attach", "Concatenate", or "Insert".
Families of commands are grouped by nouns. It is quickly apparent that "Get-
Service", "Start-Service", "Stop-Service", and "Restart-Service" are all related. As such,
these cmdlets accept a similar set of parameters and return a similar set of objects.
1) Adhering to the Microsoft standard, which of the options below would be the
best name for a cmdlet that retrieves information on the Network Configuration?
Retrieve-Network_Configuration
Get-Network_Configuration
Get-NetworkConfiguration
Retrieve-NetConf
Get-NetConf
2) Which of these is a standard PowerShell Verb?
Clear
Unmark
Unset
Erase
Release

6
1) Adhering to the Microsoft standard, which of the options below would be the
best name for a cmdlet that retrieves information on the Network Configuration?
Get-NetworkConfiguration
Cmdlets are named Verb-Noun and the noun is the full name without
underscores between words
2) Which of these is a standard PowerShell Verb?
Clear
Only "clear" is in the list of standard verbs

7
Most cmdlets take additional parameters (or arguments). Parameter names are
preceded by a dash (-). One such parameter, used by the cmdlet "Get-Service", is
"Name". The command "Get-Process -Name svchost" will "get" the objects
representing each "process" with the "name" "svchost". Some cmdlets accept
positional parameters, meaning a parameter name is not required since it is assumed
from its position on the command line. "Get-Service's" "Name" is such a parameter,
and the above command can be shortened to "Get-Process svchost". It is pretty
convenient that cmdlets can be shortened and some parameter names can be
dropped.

8
In Bash and cmd.exe scripting, you often spend a great deal of time interfacing
between applications. In other words, you capture the output of one command,
parse out the pieces of data that you need (such as an IP address), and then pass that
information on to the next command. Wouldn't it be nice if each command
automatically understood the output of the other? Besides being easier to read, it is
much easier to write.
Well, as you probably guessed, that is one of the benefits of the object-oriented
nature of PowerShell. In PowerShell, every "cmdlet" has an understanding of the
output from other cmdlets, and they can be tied together with powerful results. The
objects returned from each cmdlet are understood by other cmdlets. A simple glance
at the command reveals which property is being used, and it doesn't require extra
effort or intimate knowledge of the output in "field 2."
For example, it isn't immediately clear what is being done in the command below (it
gets a list of the process ID's for each running process).
$ ps aux | cut -d' ' -f2
While the equivalent PowerShell command is much more readable.
PS C:\> Get-Process | Select ID
A new object type (or set of objects) may be encountered for the first time and you
may not know what properties and methods are available to interact with the object.
How do we know which properties and methods are available? The cmdlet "Get-
Member" can be used to show available properties, methods, and events as shown
above (the output has been modified for brevity).
We can kill a process by calling the Kill method.
PS C:\> $a = Get-Process spoolsv
PS C:\> $a.Kill()
Or more tersely:
PS C:\> (Get-Process spoolsv).Kill()
The real "power" in PowerShell is using the objects with the pipeline. This pipeline
takes the output objects from one command and sends it as input to the next
command. Simply use the pipe character ("|") to link our two commands. Here is a
real-world example of the use of the pipeline:
PS C:\> Get-Service | Where-Object { $_.Status -eq
"Running" } | Sort-Object -Property Name
This command will return all the services, filter for the running ones, and sort them
by name. Don't worry about the syntax of "Where-Object" for now, that will be
covered in a bit.
While this is highly dangerous, we could even use this same syntax to stop all running
services (don't try this at home!):
PS C:\> Get-Service | Where-Object { $_.Status -eq
"Running" } | Stop-Service
All sorts of commands can be chained together to create some really powerful and
flexible commands.
1) PowerShell's cmdlets are aware of the data passed from other cmdlets. This is
because PowerShell is _______ based.
text
object
interpreter
scalar
compiler
2) Tab Completion can be used to increase typing efficiency and accuracy. Which
benefit does it NOT provide?
Tab complete cmdlet names
Cycle through cmdlet names
Tab complete parameter names
Cycle through parameter names
Tab complete parameter values
Answers
1) PowerShell's cmdlets are aware of the data passed from other cmdlets. This is
because PowerShell is _______ based.
Object
The objects allow all the properties to be passed to cmdlets further down the
pipeline, allowing other cmdlets to access the objects themselves instead of
just text output from other commands.

2) Tab Completion can be used to increase typing efficiency and accuracy. Which
benefit does it NOT provide?
Tab complete parameter values
The values are an arbitrary value selected by you, but the parameter names and
cmdlet names are limited and known by the shell.
Exercise Complete
This portion intentionally left blank.
Welcome to Cyber Aces, Module 3! This module provides an introduction to the
latest shell for Windows, PowerShell. In this session we'll discuss cmdlets.
This training material was originally developed to help students, teachers, and
mentors prepare for the Cyber Aces Online Competition. This module focuses on the
basics of what an operating systems is as well as the two predominant OS's, Windows
and Linux. In this session we will provide a walkthrough of the installation a Windows
VM using VMware Fusion (MacOS) and VMware Player (Windows & Linux). These
sessions include hands-on labs, but before we begin those labs we need to install the
operating systems used in those labs. We will be using VMware to virtualize these
operating systems. You can use other virtualization technologies if you like, but
instruction for their setup and use are not included in this training.
The three modules of Cyber Aces Online are Operating Systems, Networking, and
System Administration.
For more information about the Cyber Aces program, please visit the Cyber Aces
website at https://CyberAces.org/.
Is this section, we'll spend time discussing cmdlets. We'll cover the help system and
how to find cmdlets. We'll also discuss aliases for cmdlets and some of the common
cmdlets.
The most important commands to know are the ones that get more help and
information. The two most important commands in this regard are Get-Help and Get-
Command. The Get-Help cmdlet is the PowerShell equivalent of "man" on Linux. It
displays information on PowerShell's commands and concepts. When used with the
name of a cmdlet, it returns the synopsis and syntax for the command. To get
examples of the cmdlet in use, use the "-Examples" switch. For the full output,
including synopsis, syntax, parameter descriptions and examples, use the "-Full"
switch. The formatting of Get-Help's output is very similar to that of Linux's man.
The Get-Command cmdlet "gets basic information about cmdlets and other elements
of Windows PowerShell commands." Its most common use is to find other cmdlets
based on a verb or noun by using the "-Verb" or "-Noun" parameters. To see all the
commands used to manage services we can use the following command:
PS C:\> Get-Command -Noun Services
The -Verb parameter is available as well. To list all cmdlets that use the Get verb we
can use the following command:
PS C:\> Get-Command -Verb Get
The -Module parameter can be used to find command specific to a loaded module.
Many 3rd party products have a PowerShell interface which loads another module.
We can list all loaded modules with “Get-Module”. To see the commands specific to
a loaded module we use “Get-Command -Module ModuleName”.
All of these parameters take wildcard characters and they can be combined to
provide a more granular search.
PS C:\> Get-Command -Module Vm* -Verb Get
Aliases are a very handy way to simplify the commands that you use and make typing
faster and more efficient. Many commands that are implemented in CMD or Bash are
aliased using the respective shell's command name. To copy an item in CMD the
command "copy" is used, in Bash the command is "cp". Both of these are aliases for
the "Copy-Item" cmdlet.
Many times it is useful to create an alias for a commonly used command. The most
commonly used command without an alias is Select-String and the common alias is
ss. To create the alias for the command we use this command:
PS C:\> Set-Alias -Name ss -Value Select-String
The Set-Alias takes positional parameters, so it knows the first input is the alias name
and the second is the command we want to alias. We could type this command
instead.
PS C:\> Set-Alias ss Select-String
1) What is the best way to see which cmdlets are available to manipulate or get the
list of commands entered during the current session?
Get-Command History
Get-Command -Noun History
Get-YeOldeCommands
Get-Command -Noun History -Verb History
Get-Command -Verb History
2) Which command would find Aliases for the Get-ChildItem cmdlet?
Get-ChildItem -Help
Get-Help Get-ChildItem
Get-Alias –Definition Get-ChildItem
Get-Command Get-ChildItem
Get-ChildItem -?
1) What is the best way to see which cmdlets are available to manipulate or get the
list of commands entered during the current session?
Get-Command -Noun History
This will find commands that have the noun of History and will show the
commands to Get, Add, Clear, and Invoke items in the command history
2) Which command would find Aliases for the Get-ChildItem cmdlet?
Get-Alias –Definition Get-ChildItem
The cmdlet we need to use is Get-Alias with the –Definition parameter.
Above is a list of the common cmdlets and the equivalent commands in Bash and
CMD.
At first glance, you might wonder why cmd.exe's "dir" command has been replaced
by something as weird sounding as "Get-ChildItem". Well, "Get-ChildItem" does more
than just list files and directories, and that is why the name is more generic. This
cmdlet returns objects from any container, and the filesystem is just one of many
containers. For example, it can also be used to list the system certificates ("Get-
ChildItem cert:") and the registry ("Get-ChildItem HKLM:").
1) Which command would display a directory listing where the output is sorted
alphabetically?
Get-ChildItem a b c d e f g h I j k i m n o p q r s
t u v w x y z
Get-ChildItem | Sort-Object -Property Name -
Descending
Get-ChildItem | Sort-Object -Property Name
Sort-Object -Property Name | Get-ChildItem
Get-ChildItem | Sort Alphabetically
2) Which of these commands would NOT display the contents of a text file?
type file.txt
cat file.txt
Get-Content file.txt
view file.txt
gc file.txt
1) Which command would display a directory listing where the output is sorted
alphabetically?
Get-ChildItem | Sort-Object -Property Name
The output of our directory listing, from Get-ChildItem, is piped into the Sort-
Object cmdlet where sorting is done on the Name property. By default, the
sorting is done in Ascending order so no other parameters or switches are
necessary.
2) Which of these commands would NOT display the contents of a text file?
view file.txt
There is no view command or default alias in PowerShell
Exercise Complete
This portion intentionally left blank.
Welcome to Cyber Aces, Module 3! This module provides an introduction to the
latest shell for Windows, PowerShell. In this session we'll discuss additional syntax as
well as scripting and variables.
This training material was originally developed to help students, teachers, and
mentors prepare for the Cyber Aces Online Competition. This module focuses on the
basics of what an operating systems is as well as the two predominant OS's, Windows
and Linux. In this session we will provide a walkthrough of the installation a Windows
VM using VMware Fusion (MacOS) and VMware Player (Windows & Linux). These
sessions include hands-on labs, but before we begin those labs we need to install the
operating systems used in those labs. We will be using VMware to virtualize these
operating systems. You can use other virtualization technologies if you like, but
instruction for their setup and use are not included in this training.
The three modules of Cyber Aces Online are Operating Systems, Networking, and
System Administration.
For more information about the Cyber Aces program, please visit the Cyber Aces
website at https://CyberAces.org/.
Is this section, you will be introduced to PowerShell and some basic syntax.
As with any shell, you can write scripts to automate common tasks, and this can make
life a lot easier. Scripts can make boring and repetitive tasks much easier and quicker.
Why ever do the same thing twice?
These scripts have the extension ".ps1", and do not require any special headers. The
syntax of variables and commands in scripts is the same as that used on the
command line. However, there are a few security features surrounding the execution
of these script files.
The first security feature is, by default, double clicking on a ".ps1" file will not execute
the script, but rather will open it in a text editor. This prevents the inadvertent
execution of script files. To manually execute a script, it must be run from the
command line.
The second security feature is that, by default, no scripts can be run. The default
"ExecutionPolicy" is "Restricted." In this mode, PowerShell only operates as an
interactive shell.
If you need to run scripts, the most secure setting is "AllSigned." With this setting,
scripts can run, but all scripts and configuration files must be signed by a trusted
publisher. Even scripts written on the local computer must be signed, and that can
make writing and debugging scripts difficult. Because this setting can be a pain, the
most common setting is "RemoteSigned." It is the same as "AllSigned," except locally
written scripts do not have to be signed. With "RemoteSigned", any scripts or
configuration files downloaded from the Internet, e-mail, or IM still must be signed.
Use the "Set-ExecutionPolicy" cmdlet to change this setting.
PS C:\> Set-ExecutionPolicy AllSigned
PS C:\> Set-ExecutionPolicy RemoteSigned
These commands can be run to change the execution policy to "AllSigned" or
"RemoteSigned" respectively. Please note that you may need to run PowerShell with
elevated permissions to use the "Set-ExecutionPolicy" cmdlet!
PowerShell can be executed with a specific policy using the -ExecutionPolicy
parameter (-exec for short):
PS C:\> powershell.exe -exec bypass
1) By default, does PowerShell allow you to run scripts that you have written on the
local computer?
Yes
No
2) What is the noun used in the cmdlets to view and set whether scripts can be
executed?
ExecutionPolicy
AllowScripts
AllSigned
RemoteSigned
Execution_Policy
1) By default, does PowerShell allow you to run scripts that you have written on the
local computer?
No
The default policy of "Restricted" prevents running of all script files
2) What is the noun used in the cmdlets to view and set whether scripts can be
executed?
ExecutionPolicy
Remember, nouns don't contain the underscore character (_)
Variables are useful for storing data that you want to use later. Variables in
PowerShell are preceded by a dollar sign ("$"), so we could use the following to store
the number 7 in the variable "$a":
PS C:\> $a = 7
We can than output the variable "$a" just by typing it on the command line.
PS C:\> $a
7
Variables can store collections of objects, such as the output of a directory listing.
PS C:\> $o = Get-ChildItem
PS C:\> $o

Directory: C:\

Mode LastWriteTime Length Name


d-r-- 1/2/2011 1:27 PM Program Files
d-r-- 12/8/2010 8:56 AM Users
d---- 12/31/2010 11:50 AM Windows
-a--- 6/10/2009 4:42 PM 24 autoexec.bat
-a--- 6/10/2009 4:42 PM 10 config.sys
We can also explicitly cast a variable to be of a certain type by using "[type]" so that it
will only store values of the given type. Here "$a" is declared as an integer and set to
"7". Let's see what happens when "$a" is set to an invalid value.
PS C:\> [int]$a = 7
PS C:\> $a = "Seven"
Cannot convert value "Seven" to type "System.Int32".
Error: "Input string was not in a correct format."
PowerShell throws an error since the string "Seven" is not an integer.
The most common mistake with arrays is the "Off-by-One" error, when the
programmer forgets that the index is base 0 and accesses the wrong item in an array
or attempts to access the last item in an array and uses a non-existent index number.
Arrays are just a collection of objects. They can be created manually:
PS C:\> $days= "Sun","Mon","Tue","Wed","Thu","Fri","Sat"
...or they can be from the output of another command:
PS C:\> $files = Get-ChildItem C:\
Both the "$days" and "$files" variables are arrays. We can access an item in the array
using square brackets ([]). PowerShell arrays are base zero, meaning the first item is 0.
PS C:\> $days[0]
Sun
Multiple items can be accessed like this:
PS C:\> $days[1..3]
Mon
Tue
Wed
PS C:\> $days[2,4,6]
Tue
Thu
Sat
The last item in an array can be accessed by counting backwards:
PS C:\> $days[-1]
Sat
The Current Pipeline object ($_) is used a lot in PowerShell. It is used when iterating
over a number of objects or for filtering with the Where-Object cmdlet. We'll use this
variable quite a bit towards the end of this module. The use of this variable is not
required in PowerShell version 3 which ships with Windows 8 and later.
In PowerShell v1 and v2, the Where-Object command is used similar to this:
PS C:\> Get-Process | where {$_.CPU -gt 25}
…but in v3 and later it can be shortened to this:
PS C:\> Get-Process | where CPU -gt 25
The Get-ChildItem (aliases of ls or dir) can be used to view the variables currently in
use:
PS C:\> Get-ChildItem variable:
PS C:\> dir variable:
PS C:\> ls variable:
1) Will this series of commands throw an error?
PS C:\> $a = 12
PS C:\> $a = "Rodgers"
2) What is the name of the $_ variable?
Current Object
Current Pipeline Object
Iterator Object
Filter Object
Null
1) Will this series of commands throw an error?
PS C:\> $a = 12
PS C:\> $a = "Rodgers"
No, PowerShell variables can contain any "type" of data, unless explicitly
declared using [typename]
2) What is the name of the $_ variable?
Current Pipeline Object
This object is used in ForEach-Object (alias %) loops and the Where-Object
(alias ?) filter. This variable is used a lot in PowerShell.
If a cmdlet returns output and you would like to access a property, method, or item
then wrap it in parenthesis and then use the operator in question.
As previously mentioned, the output of cmdlets are objects. Objects have properties
that we may need to access. For example, the Get-Date cmdlet returns a Date Object
that has a DayOfWeek property. To get the day of the week we need to get the
current date and then access that property.
PS C:\> (Get-Date).DayOfWeek
Tuesday
Similarly, the Get-ChildItem command will return a list of objects and to access the
first object (technically the 0th) we need to wrap it in parenthesis to finish the
command and then access the first item in the array.
Curly braces are used with "script blocks," which are essentially commands inside of
commands. This is most commonly used with "Where-Object", "ForEach-Object", and
control structures like the "If", "While", and "Switch" statements.
Square brackets have a number of uses in PowerShell: Regular Expressions, Type
Declaration, and accessing an item in an array.
Regular expressions, also called "regex", allow for very flexible and specific searching.
This is a very deep subject; in fact, multiple books have been written on just Regular
Expressions. We won't discuss this in depth, but suffice it to say that the values inside
the brackets are part of the search set. For example, the set of "[a-eh]" includes "a",
"b", "c", "d", "e", and "h". In a practical example, the command below will get all files
and folders beginning with "U" or "P".
PS C:\> Get-ChildItem [UP]*

Directory: C:\

Mode LastWriteTime Length Name


d-r-- 1/2/2011 1:27 PM Program Files
d-r-- 12/8/2010 8:56 AM Users
What a nifty way to search.
Square brackets are also used to cast an object or declare a variable with a specific
type (as shown in the "Variables" section). Also, the square brackets are used to
access items in an array (see the "Arrays" slide).
For the most part, the single and double quotes are nearly interchangeable. The only
difference is PowerShell tries to expand text inside double quotes, but not inside
single quotes. Here is an example:
PS C:\> $a = "Inigo Montoya"
PS C:\> Write-Host "Hello, my name is $a"
Hello, my name is Inigo Montoya
PS C:\> Write-Host 'Hello, my name is $a'
Hello, my name is $a
You can accomplish the same thing with double quotes, but you need to use the
backtick as a delimiter to escape the dollar sign:
PS C:\> Write-Host "Hello, my name is `$a"
Hello, my name is $a
If you want to use a variable inside quotes, you simply use the variable; but what if
you want to access a property or a specific array index of that variable? Let's start
with the basic version of the command by just accessing the variable.
PS C:\> $a = Get-Item Windows
PS C:\> echo "The variable `$a contains $a"
The variable $a contains C:\Windows
Now, what if we try to access the "CreationTime" property of the object "$a"?
PS C:\> echo "The creation time of `$a is
$a.CreationTime"
The creation time of $a is C:\Windows.CreationTime
Uh oh, that doesn't work! To access a property in a string, we need to wrap it in "$(
)", called the sub-expression operator. Here is the right way of doing the same thing.
PS C:\> echo "The creation time of `$a is
$($a.CreationTime)"
The creation time of $a is 02/13/2009 17:31:30
1) Assuming the current directory contains only two files named file.txt and
otherfile.txt. What is the output of the following two commands?
$a = ls [fo]* | Sort-Object –Name
echo "The length of `$a is $($a.Length) and the
first file is $($a[1])"
a. The length of C:\file.txt C:\otherfile.txt is 2
and the first file is C:\otherfile.txt
b. The length of $a is 2 and the first file is
C:\otherfile.txt
c. The length of $a is 2 and the first file is
C:\file.txt
d. The length of `$a is $($a.Length) and the
firstname is $($a[1])
2) Curly Braces are used for which of the following?
Script Blocks
Arrays
Type declarations
Order of operations
1) Assuming the current directory contains only two files named file.txt and
otherfile.txt. What is the output of the following two commands?
$a = ls [fo]* | Sort-Object –Name
echo "The length of `$a is $($a.Length) and the
first file is $($a[1])"
a. The length of C:\file.txt C:\otherfile.txt is 2
and the first file is C:\otherfile.txt
b. The length of $a is 2 and the first file is
C:\otherfile.txt
c. The length of $a is 2 and the first file is
C:\file.txt
d. The length of `$a is $($a.Length) and the
firstname is $($a[1])
2) Curly Braces are used for which of the following?
Script Blocks
Arrays
Type declarations
Order of operations
Exercise Complete
This portion intentionally left blank.
Welcome to Cyber Aces, Module 3! This module provides an introduction to the
latest shell for Windows, PowerShell. In this session we will discuss flow control and
output in PowerShell.
This training material was originally developed to help students, teachers, and
mentors prepare for the Cyber Aces Online Competition. This module focuses on the
basics of what an operating systems is as well as the two predominant OS's, Windows
and Linux. In this session we will provide a walkthrough of the installation a Windows
VM using VMware Fusion (MacOS) and VMware Player (Windows & Linux). These
sessions include hands-on labs, but before we begin those labs we need to install the
operating systems used in those labs. We will be using VMware to virtualize these
operating systems. You can use other virtualization technologies if you like, but
instruction for their setup and use are not included in this training.
The three modules of Cyber Aces Online are Operating Systems, Networking, and
System Administration.
For more information about the Cyber Aces program, please visit the Cyber Aces
website at https://CyberAces.org/.
Is this section, you will be introduced to PowerShell's flow control and output
cmdlets.
Operator Description Example Usage
-eq Equal to 2 + 2 -eq 4
-lt Less than 1 -lt 2
-gt Greater than 2 -gt 1
4 -ge 4
-ge Greater than or Equal to
4 -ge 3
1 -le 1
-le Less than or equal to
13 -le 37
-ne Not equal to 13 -ne 37
-not Logical Not -not (2 -eq 1)
! Logical Not !(2 -eq 1)
-and Logical And (2+2 -eq 4) -and (1+1 -eq 2)
-or Logical Or (2+2 -eq 0) -or (1+1 -eq 2)
Match using the wildcard
-like "PowerShell" -like "*shell"
character
-notlike Opposite of -Like "PowerShell" -notlike "*bash"
Matches using a Regular
-match Expression and populates the "Sunday" -match "[A-Z]*"
$matches variable
Does not match on Regular
-notmatch "Sunday" -notmatch "[0-9]*"
Expression, populates $matches
-contains Containment operator $days -contains "sun"
-notcontains Opposite of contains $days -notcontains "blah"
Replaces (does not return a "Monday" -replace "Fri"
-replace
Boolean) Output: Friday

4
1) What is the proper syntax to check if "$a" is greater than 4?
$a >> 4
$a -gt 4
$a -ge 4
$a gt 4
$a > 4
2) Which of these commands will check if "$a" ends with string "find me"?
$a -contains "*find me"
$a -like "find me"
$a -like "*find me"
$a -find "find me"
$a -endswith "find me"
1) What is the proper syntax to check if "$a" is greater than 4?
$a -gt 4
The > operator is used for redirection (see Get-Help about_redirection)
2) Which of these commands will check if "$a" ends with string "find me"?
$a -like "*find me"
The asterisk at the beginning means it will match anything at the beginning,
since there is no asterisk at the end it must exactly match "find me".
The "If..Then..Else" statement is one of the most basic methods of controlling the
flow of a script. The basic syntax of the "If" statement in PowerShell is:
if (condition) {do stuff}
elseif (condition) {do other stuff}
elseif (condition) {do other stuff}
...
else {do something else}
That is a bit of pseudocode, so let's use a real example to see how it works. Let's say
we have a variable "$a" and we want to know if it is zero.
if ($a -eq 0) {"zero"}
No output, which must mean the variable is not zero. Let's modify our "If" statement
to be a bit more verbose.
($a –eq 1) {"zero"} else {"non-zero"}
Now the "If" statement tells us if the variable is non-zero or not, but what if the
variable is positive.
if ($a –eq 0){"zero"} elseif ($a -gt 0) {"positive"}
No output, we forgot to output something if "$a" is negative.
if ($a –eq 0) {"zero"} elseif ($a -gt 0) {"positive"}
else {"negative"}
We've used our "If" statement to let us know if our variable is zero, positive, or
negative. There can be multiple "ElseIf" sections. Also, the script block, denoted with
curly braces ({ }), can contain all sorts of PowerShell magic, including other "If"
statements.
The "Where-Object" cmdlet (alias "?") was lightly addressed in the variables section,
but it deserves more attention. Let's use "Where-Object" to find all files bigger than
20MB.
PS C:\> ls -Recurse | ? { $_.Length -ge 20000000 }
The "ls" is an alias for "Get-ChildItem". As we saw in the "Common Cmdlets" section,
"Get-ChildItem" does a directory listing. The "-Recurse" option recursively searches
each directory.
Each object is passed down the pipeline, one at a time (represented by "$_"), and
each object's length (size) is checked to see if it is greater than 20MB. If it is, then the
object is passed further down the pipeline. If not, it is discarded. In this case, "further
down the pipeline" is just output. Let's get a little more hi-tech with this example and
search for files that are greater than 20MB and have the ".zip" extension.
PS C:\> ls -Recurse | ? { $_.Length -ge 20000000 -and
$_.Extension -eq ".zip" }
Directory: C:\

Mode LastWriteTime Length Name


-a--- 10/10/2009 10:10 PM 31415926 mybig.zip
Note: PowerShell version 3 does not require the curly braces or the current pipeline
object so the following works in PowerShell version 3.
PS C:\> ls -Recurse | ? Length -ge 20000000 -and
Extension -eq ".zip"
The ForEach-Object cmdlet is incredibly powerful. Linux has a command similar to
this, xargs, but it is not nearly as powerful. If multiple commands are nested it is quite
difficult to write (and read) the xargs command. For example, if we wanted to read
the contents of a csv file which contained a list of large files, then move those files if
they are still too big:
PS C:\> Import-Csv largefiles.csv | % { Get-Item
$_.FileName } | ? { $_.Length -gt 20000000 } | Move-
Item -Destination C:\StillTooBig
1. Import the csv file
2. Use the ForEach-Object cmdlet (alias %) to get the file (get-item) using the
FileName column in the csv
3. Use Where-Object to only pass files that are greater than 20MB
4. Move the file to destination, this command receives the original path from the
object passed down the pipeline
The "ForEach-Object" cmdlet is very powerful, and extremely useful. If you use
PowerShell at all, you will need to know this command.
The Select-Object cmdlet is used for removing properties from objects as they pass
down the pipeline. It can also be used to select the first X lines, the last X lines,
and/or skip the first X lines.
One of the most powerful, but advanced options, is to add properties to objects as
they move down the pipeline. If you imported a csv file and it included two columns,
firstname and lastname, you could create another column named Fullname using a
command similar to the one below.
PS C:\> Import-Csv users.csv | Select *,
@{Name="FullName"; Expression={$_.Firstname + " " +
$_.Lastname}}
By default, most commands just display the basic properties of an object. That is a
good thing, because otherwise the screen would be mostly cluttered with useless
information. But what if we do want more or all of the information? Let's see how to
view the objects in different methods. By default, the "Get-Process" cmdlet's output
is similar to this:
PS C:\> Get-Process
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
711 24 20024 31196 203 13.23 1524 explorer
...
The output above is the "Table" format, and can be explicitly chosen by using the
following command:
PS C:\> Get-Process | Format-Table
We can use the "Format" cmdlets to show specific properties. Also, here is the alias
for Format-Table (ft).
PS C:\> ps | ft Name, Id
Name Id
explorer 1524
The other most notable output format is the "List" format. To output the results in a
list format, use "Format-List" or the alias "fl".
PS C:\> ps | fl
Id : 1524
Handles : 712
CPU : 13.6396128
Name : explorer
...
Uh oh, in this case the list format actually displays less information. This isn't typically
the case, but it does this for "Process" objects. To display everything use the * for the
list of properties.
PS C:\> ps | fl *
The Out-File cmdlet is used to write output from the pipeline to a file. However, it
writes the content using Unicode. Unicode represents each character using more than
one byte and it may not work with some editors or parsers. Unicode does support
hundreds of different character sets and the special characters associated with those
languages.
Reference: https://en.wikipedia.org/wiki/Unicode
The Export-CSV cmdlet is very powerful. It is very handy for parsing and
manipulating data from other sources. It can also be used to save variables or arrays
for later use. Each row will be an object, and each column is a property of that object.
To export objects, simply pipe it into Export-CSV. To retrieve the data, use the Import-
CSV cmdlet to read the csv file.
1) Which of these commands will find all files that end with the extension ".txt"?
ls -Recurse -Extension -eq ".txt"
ls -r | ? { $_.Extension -eq ".txt"}
ls -r | ? { $_.Extension ".txt"}
ls -r | ? { $_.Extension == ".txt"}
ls -r | ? { $_.Extension = ".txt"}
2) Which command would find all files larger than 20MB where the file name begins
with "archive"?
ls -r | ? { $_.Length -gt 20000000 && $_.Name -like "archive" }
ls -r | ? { $_.Length -gt 20000000 and $_.Name -like "archive*" }
ls -r | ? { $_.Length -gt 20000000 -and $_.Name -like "archive*" }
ls -r | ? { $_.Length -gt 20000000 -and $_.Name -like "*archive*" }
ls -r | ? { $_.Length -gt 20000000 -and $_.Name -like "archive" }
1) Which of these commands will find all files that end with the extension ".txt"?
ls -r | ? { $_.Extension -eq ".txt"}
The proper comparison operator is "-eq"
2) Which command would find all files larger than 20MB where the file name begins
with "archive"?
ls -r | ? { $_.Length -gt 20000000 -and $_.Name -
like "archive*" }
The proper Logical AND operator is -and
Since "archive" must be at the beginning we don't use a wildcard (*) in front;
however, we do need it at the end of the search string. Without the wildcard
the statement will only match a file that is exactly named "archive" and won't
match the file "archive1.zip"
Exercise Complete
Is this section, you will be introduced to PowerShell's flow control and output
cmdlets.
Welcome to Cyber Aces, Module 3! This module provides an introduction to the
latest shell for Windows, PowerShell.
This training material was originally developed to help students, teachers, and
mentors prepare for the Cyber Aces Online Competition. This module focuses on the
basics of what an operating systems is as well as the two predominant OS's, Windows
and Linux. In this session we will provide a walkthrough of the installation a Windows
VM using VMware Fusion (MacOS) and VMware Player (Windows & Linux). These
sessions include hands-on labs, but before we begin those labs we need to install the
operating systems used in those labs. We will be using VMware to virtualize these
operating systems. You can use other virtualization technologies if you like, but
instruction for their setup and use are not included in this training.
The three modules of Cyber Aces Online are Operating Systems, Networking, and
System Administration.
For more information about the Cyber Aces program, please visit the Cyber Aces
website at https://CyberAces.org/.
In this section, we use the knowledge we gained in some practical scenarios.
Say we have a network, where we would like to lookup the name of each device on
the network. We can use the "Range" operator in conjunction with our "ForEach-
Object" loop to pull this off.
PS C:\> 1..254 | % { Write-Output "192.168.0.$_" }
192.168.0.1
192.168.0.2
192.168.0.3
...
The "Range" operator is just a quick way of counting. The results are piped into our
"ForEach-Object" loop where we display, via "Write-Output", the string. Instead of
just printing the IP address, we could ping every IP address.
PS C:\> 1..254 | % { ping "192.168.0.$_" }
We could just as easily replace "ping" with "nslookup" or numerous other network
commands. The possibilities are endless.
Note: This command will also work without using quotes, but will not work with
single quotes.

4
This is the proverbial, "I brought you into this world, and I'll take you out." First, we
need to bring a process into this world.
Start-Process notepad
That was easy, but we could have just typed "notepad" and accomplished the same
thing. But we can do something cooler; we can use Notepad to open a file and
maximize the window.
Start-Process notepad -ArgumentList myfile.txt
-WindowStyle Maximized
Using the alias, positional parameters, shortened parameter names, and shortened
options we can squish the command to this:
start notepad myfile.txt –win max
What if we wanted to print the file? We can do that too, and we can use the viewer
associated with the file. It is as if we right clicked on the file and selected "Print."
Start-Process myfile.pdf -Verb Print
Ok, so starting processes isn't so neat, but killing them is. We can use "Stop-Process"
(alias "kill") to stop processes. We can kill based on the Process Id...
Stop-Process 1337
...or the process name:
Stop-Process -Name cmd
What if we have a user on the system named "E. Phil", and E. Phil is evil. What if he is
running executables from his desktop and we want to kill them?
ps | ? { $_.Path -like "C:\Users\ephil\*" } | kill
This command gets all the processes, filters for executables originating from E. Phil's
user path, and then kills them. We have successfully defeated E Phil, and the world is
now a safer place for shells.
1) The Blah Company is using 256 networks with a /24 CIDR mask, 10.0.0.X/24
through 10.0.255.X/24. On each network, they have a network gateway and its IP
address ends in .254 (i.e. 10.0.0.254, 10.0.1.254...). Write a command to ping
each gateway.
2) Which command will NOT kill all processes with "bad" in the process name?
a. ps -name *bad* | kill
b. ps | ? { $_.Name -like "*bad*" } | kill
c. Get-Process | Where-Object { $_.Name -contains
"*bad*" } | Stop-Process
d. kill -name *bad*
e. Get-Process -Name "*bad*" | Stop-Process
1) The Blah Company is using 256 networks, 10.0.0.X/24 through 10.0.255.X/24. On
each network, they have a network gateway and its IP address ends in .254 (i.e.
10.0.0.254, 10.0.1.254...). Write a command to ping each gateway.
One possible answer:
0..255 | % { ping 10.0.$_.254 }
This is very similar to the earlier example, the only difference is the octet
2) Which command will NOT kill all processes with "bad" in the process name?
c. Get-Process | Where-Object { $_.Name -contains
"*bad*" } | Stop-Process
The -contains operator won't work here as it is used to search an array/collection
for a matching item, not for finding a string in another string. The -match and -like
operators are used to search strings using regular expressions and wildcards
respectively.
Before we iterate through all the files in a directory, we need to figure out how to
filter out directories. Let's start by looking at a regular directory listing:
PS C:\> ls
Directory: C:\
Mode LastWriteTime Length Name
d-r-- 1/3/2011 7:14 AM Program Files
d-r-- 12/8/2010 8:56 AM Users
d---- 1/3/2011 9:58 AM Windows
-a--- 6/10/2009 4:42 PM 24 autoexec.bat
-a--- 6/10/2009 4:42 PM 10 config.sys
It looks like all the files have the "a" bit set, but that isn't a guarantee to find only
files. The "a" stands for "Archive", meaning the file has been modified since the last
backup. We need another option. We could filter out anything with the "d" bit set.
That works, but it is still a little cheesy. The best option is to look at the properties of
the objects to see if there is a better option.
PS C:\> ls | gm
If you run the command (output not shown here as it is too long), the best option is
"PSIsContainer", since it is Boolean and doesn't require string comparison of the
"mode" property, so it is faster. Directories are containers and files are not. We can
use this property with "Where-Object" (alias "?") to quickly get all the file objects.
Also, Get-ChildItem doesn't return hidden items, but we can use the "-Force" option
to find those files as well.
PS C:\> ls -fo | ? { !$_.PSIsContainer }
Directory: C:\
Mode LastWriteTime Length Name
-a--- 6/10/2009 4:42 PM 24 autoexec.bat
-a--- 6/10/2009 4:42 PM 10 config.sys
-a-hs 1/3/2011 7:36 AM 1073741824 pagefile.sys
Ok, so now we have only files. Let's do something with them.
To search a file for a specific string, we can use "Select-String". This cmdlet is similar
to Linux's "grep".
PS C:\> Select-String -path *.txt -Pattern password
user1.txt:1:my password is P@ssw0rd1
user3.txt:1:my password is blank
...or shorter:
PS C:\> Select-String password *.txt
user1.txt:1:my password is P@ssw0rd1
user3.txt:1:my password is blank
The "Select-String" cmdlet searches the file for the search pattern. The pattern can
even be a Regular Expression. One notable limitation of "Select-String" is its inability
to recursively search the filesystem. To do the recursive search, we have to use "Get-
ChildItem" in conjunction with "Select-String". We can use the -fi[lter] option to
only look in .txt files, -r[ecursive] to walk the file system, and -fo[rce] to look in
hidden files and directories.
PS C:\> ls -fi *.txt -r -fo | select-string password
user1.txt:1:my password is P@ssw0rd1
user3.txt:1:my password is blank
\Users\john\Desktop\p.txt:1:my password is 4dm1n1st4t0r
Import-CSV is an extremely powerful cmdlet. It is used to read all sorts of input. Many
times output from other programs is saved in a CSV format where each field is
separated with spaces, commas, or tabs. This command will quickly import the data
and allow you to use cmdlets to filter, format, and process the data.
Let's say we have a text file containing these three lines of text that we want to
manipulate with PowerShell:
John Doe 90
Jane Doe 89
Freak Bean 97
Before we can use the data, we need to parse it. We could do it manually, but Import-
CSV is much easier. Commonly, a .csv file contains a header and the fields are comma
(or tab) delimited. We can tell the cmdlet to use a different delimiter character and
we can provide header information.
PS C:\> Import-Csv -Delimiter " " -Path scores.txt -
Header "First", "Last", "Score"
First Last Score
----- ---- -----
John Doe 89
Jane Doe 90
Frank Bean 97
Now that the data has been objectified, we can use other cmdlets to sort, parse,
manipulate, or measure the data.
Let's take the data and sort it by the score:
PS C:\> Import-Csv -Delimiter " " -Path scores.txt -
Header "First", "Last", "Score" | sort -
Property Score -Descending
First Last Score
----- ---- -----
Frank Bean 97
Jane Doe 90
John Doe 89
Once the data is converted to objects, PowerShell can be leveraged to perform
statistics or other operations on the data. The Measure-Object cmdlet is just one of
many options.
PS C:\> $scores = Import-Csv -Delimiter " " -Path
scores.txt -Header "First", "Last", "Score"
PS C:\> $scores | Measure-Object -Property Score -Ave
-Min –Max
Count : 3
Average : 92
Sum :
Maximum : 97
Minimum : 89
Property : Score
Exercise
1) Which command could produce the following output?
The file aaa.txt has a length of 12 bytes.
dir | % { "The file $_ has a length of $Length bytes." }
dir | % { "The file $_ has a length of `$_`.Length bytes." }
dir | % { "The file $_ has a length of $_.Length bytes." }
dir | % { "The file $_ has a length of $($_.Length) bytes." }
dir | % { "The file $_ has a length of ($_.Length) bytes." }

2) Which filter can be used with the "Get-ChildItem" cmdlet (alias "ls", "dir" and
"gci") to find all files modified in the past day?
? { $_.LastAccessTime -ge (Get-Date).AddDays(-1) }
? { $_.LastAccessTime > (Get-Date).AddDays(-1) }
? { -not $_.PSIsContainer && $_.LastAccessTime > (Get-Date).AddDays(-1) }
? { -not $_.PSIsContainer && $_.LastAccessTime -ge (Get-Date).AddDays(-1) }
? { -not $_.PSIsContainer -and $_.LastAccessTime -ge (Get-Date).AddDays(-1) }
Answers
1) Which command could produce the following output?
The file aaa.txt has a length of 12 bytes.
dir | % { "The file $_ has a length of $($_.Length) bytes." }

In a string you have to use the sub-expression operator to expand the object and its
property
2) Which filter can be used with the "Get-ChildItem" cmdlet (alias "ls", "dir" and "gci")
to find all files modified in the past day?
? { -not $_.PSIsContainer -and $_.LastAccessTime -ge (Get-Date).AddDays(-1) }

This is the only option using the correct Logical AND (-and) and the correct
comparison operator (-ge)
We've learned about the newest shell in Windows, how to interact with it, and basic
scripting. This shell is the most advanced method of interacting with Windows and
Windows Server Software and being skilled in its use will provide a distinct advantage
in the real world vs. those "stuck" with the GUI.

You might also like