Day 5
Day 5
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:\
Directory: C:\
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:\
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.