You are on page 1of 106

Introduc)on

to Microso. PowerShell for Security Professionals


By Carlos Perez Carlos_Perez@darkoperator.com

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

For whom is this Class?


Security Professionals that need to audit, secure or penetrate Windows environments. Security Professionals that consume data generated by other tools in a Windows Environment. Security Professionals that like to build their own tools and automate tasks.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

Why PowerShell
PowerShell now forms part of Microso. Common Engineering Criteria for Server Products. More exibility and capabili)es than VBScript or CMD.exe. Because we are smarter than GUI Clicking admins and want to automate our work in a more ecient and reliable way.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

What is PowerShell
Command shell with scrip)ng capabili)es based on other shells like Bash and scrip)ng languages like Perl The shell operates with objects vs a command prompt or *nix shell that operates with text Designed for management and automa)on

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

What is PowerShell
PowerShell can leverage on Windows:
WMI COM .Net Framework ADSI Loading of DLLs

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

PowerShell v2 Requirements
Comes Pre-Installed on Windows 7 and 2008R2 Requires .Net Framework 3.5 or above For Windows XP and 2003 you need to download it from Microso. in the download center as KB968930 or hgp://www.microso..com/ powershell

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

PowerShell v2 Requirements
ISE is only installed on Windows 7 on 2008 R2 it is a feature that needs to be install from Server Manager On Windows 2008 in Features inside Server Manager the version that comes is Version 1.0 and there is no ISE for v1 Can not be installed side by side with v1

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

PowerShell v3 Requirements
Comes Pre-Installed on Windows 8 and 2012 Requires .Net Framework 4.0 or above Can be installed on Windows 7 SP1 and Windows 2008 R2 from hgp://www.microso..com/ powershell It is compa)ble with v1 and v2 of PowerShell Can be installed side by side with v2
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

PowerShell v3 Requirements
Windows Remote Management v3 is a requirement for PowerShell v3

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

PowerShell v3
PowerShell v3 has both engines

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

10

PowerShell v3
In the case of Windows 8 PowerShell v2 engine can be enabled or disable via the Windows Features congura)on app

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

11

PowerShell Architectures

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

12

PowerShell as Administrator

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

13

PowerShell v3 Windows 8

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

14

PowerShell v3 Windows 8

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

15

The Console

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

16

PowerShell Shell
The PowerShell Shell allows the running of regular executables and PowerShell Cmdlets. As a scrip)ng shell it also provides access to aliases and func)ons like we have on *nix style shells. Commands that are part of cmd.exe are not available. The use of environment variables and shell variables dier.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

17

PowerShell Shell
Sub-Shells like Netsh and WMIC remain the same (Some commands Break ISE Terminal Emula)on). The shell has Cisco IOS Shell characteris)cs where only the rst unique characters of a cmdlet parameter is required.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

18

Advantages
It has Tab comple)ons where one can type the rst part of a command, op)on or directory path and hit Tab key to complete One can create Transcripts of all ac)ons taken with the transcript cmdlets (Not available in ISE) Both Windows commands and cmdlets can be ran Low memory footprint
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

19

Advantages
Requires less of the .Net Framework for it to be used.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

20

Disadvantages
Only supports single byte character sets, so non- english languages wont display properly Copy and Paste of text uses nonstandard keystrokes Oers no color coding for the commands being typed

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

21

Senng up your Environment

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

22

Senng up your Environment

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

23

Senng up your Environment

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

24

Keyboard Commands
Keyboard Le./Right Arrow Keys Crtl+Le. Arrow, Crtl+Right Arrow Keys Home End Up/Down Arrow Keys Tab F7 Insert Key Delete Key Backspace Key Ac+on Move Cursor le. and right Move Cursor one Word each )me Move Cursor to Beguining Move Cursor to End Move thru Command History Command and Op)on Comple)on Command History Window Toggle Character Inser)on/Overwrite Delete character under cursor Delete character to le. of cursor
25

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

PowerShell v2 ISE

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

26

PowerShell v3 ISE

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

27

Advantages of ISE
Color coding Keyboard Copy and Paste Tab complete for Op)ons, Commands and Paths IntelliSense on ISEv3 Command Reference Pane on ISEv3

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

28

ISE v3 Almost the Best Terminal!


Intellisense for Cmdlets and parameters with parameter help popup. Intellisense will provide values for parameters based on enumera)ons and pre-dened sets. Intellisense will perform smart matching for cmdlet names Intellisense will show path op)ons for lesystems and PSProviders Intellisense will show variables Intellisense will show for objects proper)es and methods available
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

29

ISE v3 Almost the Best Terminal!


Intellisense for history when one types # followed by Ctrl-Space

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

30

ISE v3 Almost the Best Terminal!


The terminal emula)on in PowerShell ISEv3 breaks with certain Windows Commands like WMIC, Netsh and others that create a sub-shell

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

31

History
To get a list of the commands entered in the shell one can use the up and down keyboard arrows to move thru it or use the Get-History cmdlet. To execute one of the command that are in the history buer one would enter the # symbol followed by the Id number and press the Tab key to have the shell retrieve it.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

32

History
On the shell only one can also use the F7 key to get a list of the commands entered.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

33

History
PowerShell diers from other shells in that history of the commands entered is lost when the shell is closed. Transcript cmdlets can be used to keep a log of entries in the shell:
Start-Transcript - this will save all of our commands and output to a le Stop-Transcript it will stop recording our ac)on.

The Append op)on can be used to append to the end of the le entered for the transcript.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

34

Using Help

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

35

Using Help
GUI Provides discoverability using Tool)ps, Menus and Context Menus. In PowerShell the discoverability comes from using the help system. As we preach to users, family and friends we must RTFM. The mastery of the help system is what will determine if you will be eec)ve or not with PowerShell.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

36

Using Help
To get you used to using the help system in the labs you will not be given the commands for the tasks and will be encouraged to use help to gure out the commands and op)ons.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

37

Using Help
To get you used to using the help system in the labs you will not be given the commands for the tasks and will be encouraged to use help to gure out the commands and op)ons. Many )mes you will see that using the help system is faster and even beger than using Google for many discovery tasks.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

38

Using Help
To access the help system we use the Get-Help cmdlet also aliased in the shell as help and also aliased as man The help command can be used to get help on cmdlets and topics If the author included the proper comments in his code help can also be used with help

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

39

Using Help
help [cmdlet|func+on|script|topic|provider] <op+ons> would be for genng specic help. help about will show all PowerShell conceptual topics areas. help <wildcard expression> will look for the word or expression in the )tles of the help les, if none is found it will look in the content of the help for it.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

40

Using Help
One can select what parts of a help le we want to see.
Wen used against a cmdlet with no op)ons it will show Name, Synopsis, Syntax, Descrip)on, Related Links and Remarks. When the -Detailed op)on is given it will show Parameter Informa)on and Examples. When the -Full op)on is given it will show a more detailed list of info for Parameters. When the -Examples op)on is given only examples are shown.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

41

Using Help
PowerShell also provides ways to get the latest Help informa)on.
The -online op)on will open the default web browser showing the help page for the selected cmdlet or topic. On PowerShell v3 the Update-Help cmdlet was added and it will update the help les for PowerShell. It must be ran as Administrator.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

42

Using Help - Reading Syntaxt


A cmdlet can have more than one way for it to be invoked and this can be seen in the syntax

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

43

Using Help - Reading Syntax


Required for required op)ons or values they will not be enclosed in any bracket. Op)ons or values enclosed in [ ] are op)onal Values are represent with the type they take between < > Those values that can be lists are represented as <type[ ]> Those that have a predened list of op)ons it can take are represented as < op+on1 | op+on2 | op+on3>
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

44

Using Help - Reading Syntax


When the help cmdlet is used with the -full op)on is used we get addi)onal informa)on on the parameters:
required? - species if the op)on is required or not. posi)on? - specied if the posi)on is a named one or an order one. For ordered one it will give the number of the posi)on for the value it will map to it. Default value - Default value the op)on has. Accept pipeline input? - specied if the op)on accepts input from the pipeline and if the input is by value type or by property name. Accept Wildcard Characters? - species if wildcard characters can be used.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

45

PowerShell Cmdlets

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

46

Cmdlet
PowerShell specic commands are called cmdlets. They are in the form of a <verb>-<noun> The verbs are grouped for the tasks of:
Common Communica)on Data Diagnos)c Lifecycle Other Security

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

47

Cmdlet
Cmdlets are wrigen in .Net Framework Language, most are in C#. Func+ons are like cmdlets but they are wrigen in PowerShell. Applica+ons are any type of executable that can be ran from the shell.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

48

Cmdlet
For nding what cmdlets are available the Get- Command cmdlet is used. The Get-Command cmdlet will allow for the searching of Cmdlet, Alias and Func)on using wild cards. A recommended method for using Get- Command or its alias gcm is to use the -noun and/or -verb op)on so as to lter none cmdlets or use -CommandType cmdlet
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

49

Cmdlet
cmdlets can be explored in PowerShel v3 with the Show-Command cmdlet

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

50

Cmdlet
PowerShell provides to all cmdlets a set of common parameter. Some of these parameters depending on the command do not generate any results unless the cmdlet has been coded to take advantage of them. Some of the common parameter override system default preferences only for the cmdlet in ques)on. To read on then help common provides a details on each parameter
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

51

Wildcard Characters
Many of the cmdlet op)on accept wildcards characters. In PowerShell the Wildcards Characters are: Wildcard Character Descrip+on * ? [ <start>-<end>] [ ] Matches zero or more characters, star)ng at the specied posi)on Example a*

Matches any character at the specied posi)on ?n -CommandType cmdlet Matches a range of characters name[1-20] Matches the specied characters [ab]jhones

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

52

Cmdlet
PowerShell supports Aliases for cmdlets. This are like shortcuts that can be used. To get a full list of exis)ng aliases in the current shell the Get-Alias cmdlet can be used. They should be avoided in Scripts or Func)ons since they may change or be overwrigen by accident.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

53

The Shell
PowerShell has characteris)cs not present in the old command prompt or some *nix shells since it also acts almost like a REPL (Read-Eval-Print Loop) like what we have with Ruby IRB and Python Shell. Arithme)c expressions can be entered directly in to the shell

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

54

Parenthe)cal Precedence
Parenthesis apply to commands and it is refereed to as Parenthe)cal Commands
Get-Service -ComputerName (Get-Content .\serverlist.txt)

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

55

Expression Evalua)on
Evalua)ons are determined by the le.most object. If elements are of dierent types PowerShell will try to convert the rightmost element to the same type as the le.most element.
"string" + 10 = string10 10 + "string" = Error 10 + "10" = 20

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

56

Line Con)nua)on
When working on the shell and you see the >> as part of the prompt it means your command is con)nuing in another line.
PS > Get-Service -Name "BITS >>

An open brace { , parenthesis ( , or square bracket [ will allow for con)nua)on across mul)ple lines un)l the block is closed by the corresponding } ) ] A trailing comma (the array operator) will allow for a line break un)l the next array member Double quotes and single quote can also be used but @ <string> @ is recommended
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

57

Script Block
In PowerShell it interpreters a new line or ; as the end of a command. Script Block is a special structure that contains a command or a ordered collec)on of commands a Script Block is declared by using { <command> ; command} It can be passed to cmdlets or structures that accept them (More on this later)
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

58

Extending the Shell


PowerShell provides to ways to expand the number of cmdlets, func)ons and providers available to a user. These are:
PSSnapins - They are wrigen in a .Net Language and are packaged as DLLs that get registered with the systems. MS Recommend to not use this method anymore to developers. Modules - They where introduced in v2 of PowerShell and are mainly self contained in and can be copied to system to system if dependencies are included. On v3 they added the capacity for Autoloading.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

59

Extending the Shell


On v2 modules need to be loaded by hand to be able to see the commands it contains. On v3 the commands available in modules that are located in the $env:PSModulePath variable can be listed and seen without loading the module explicitly and when the command is ran it autoloads the module.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

60

Extending the Shell


Discovering new commands from PSSnapins:
For all available PSSnapins Get-PSSnapin Registered For currently loaded PSSnapins Get-PSSnapin For lis)ng commands from a loaded PSSnapin Get- Command -PSSnapin <PSSnapin Name>

Discovering new commands from Modules:


For lis)ng all available modules Get-Module ListAvailable For Currently loaded modules Get-Module For lis)ng commands from a module Get-Command - moduel <module Name> (On v2 only loaded ones)
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

61

Extending the Shell


Loading Extensions:
On v2 to load a module the Import-Module <name> on v3 modules located on the $env:PSModulePath variable are automa)cally loaded, if not on any of those paths the path would be included with the module name. Add-PsSnapin <Name> will load a PSSnapin.

Removing Extensions:
Remove-Module <name> to unload a module. Remove-PSSnapin <name> to unload a PSSnapin
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

62

Extending the Shell


Managing autoloading of modules is done by senng the PSModuleAutoloadingPreference variable:
All - Modules are imported automa)cally on rst-use. ModuleQualied - Modules are imported automa)cally only when a user uses the module-qualied name of a command in the module <Module Name>\<Cmdlet Name> None - Automa)c impor)ng of modules is disabled in the session. To import a module, use the Import-Module cmdlet.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

63

Extending the Shell


Name conicts may happen when impor)ng new commands from extensions. PowerShell will Hide or Replace commands. Tp minimize risk of this happening import new modules with either the -NoClober parameter or the -Prex <prex> parameter One can also select what import by passing the names to the parameters Alias, Cmdlet, Func+on, and Variable
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

64

Pipeline

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

65

Pipeline On Other Shells

Command'

StdOut'

StdIn'

Command'

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

66

The Pipeline
The pipeline is what makes PowerShell so powerful as a shell. It )es commands and cmlets together in ways a regular shell can not. Mastery of the Pipeline is what makes the dierence in mastering or not PowerShell

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

67

Pipeline ByValue

cmdlet'

Objects'

(InputObject'[]'

cmdlet'

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

68

Pipeline ByValue
The Object Type has to be same from the output to of the cmdlet to the Parameter receiving it. Te Parameter mus accept input from the pipeline and it must also accept a collec)on

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

69

Pipeline ByPropertyName

cmdlet'

Objects'

ValueName'[]'

cmdlet'

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

70

Pipeline ByValue
The Object has to have a property which name matches the Parameter name Te Parameter must accept input from the pipeline and it must also accept a collec)on

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

71

Pipeline
When and object collec)on is send thru the pipeline to another cmdlet that takes a collec)on of objects each object is referred to as $_
Get-Service | where-object { $_.Status -eq "Running" }

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

72

PowerShell Objects

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

73

PowerShell Objects
Every ac)on taken inside of PowerShell is done in the context of objects. Data is moved from one cmdlet to another as a single object or collec)on of objects. Objects are composed of:
Type - What kind of objects is it. Method - Ac)on that can be taken on the object. Property - Informa)on about the state of an object

Even the data returned by a regular command is retuned as an object.


Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

74

PowerShell Objects
To get a list of the methods and proper)es an object has the Get-Member cmdlet is used. One can use the Pipe to pass an object or a collec)on of objects to Get-Member If a collec)on is given it will return the informa)on for each unique type in the collec)on.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

75

PowerShell Objects
For the manipula)on of objects we will cover rst the Operators in PowerShell since they are used against Objects and the Proper)es of objects. PowerShell operators dier from the operators of other scrip)ng and programing languages, the design reasons where to mimic those found in Shell Languages found on *nix systems. When comparisons are done PowerShell has the special variables $True and $False to represent Boolean values
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

76

Arithme)c Operators
Operator + Descrip+on Adds integers and oa)ng numbers; concatenates strings, arrays, and hash tables. Subtracts one value from another. When placed in-front of an integer it makes the numbers a nega)ve one. Divides two values. Mul)plies integers and oa)ng numbers. Copies strings and arrays the specied number of )mes. Returns the remainder of a division opera)on.

- / * %

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

77

Arithme)c Operators
Operator Descrip+on

++

Unary addi)on. Adds 1 to the variable it is used against.

--

Unary subtrac)on. Subtracts 1 from the variable it is used against.

+=, -=, /=, *= Shortcuts for taking the content of a variable and replacing it with the content plus the ac)on and a new variable like $var = $var + 10 would be $var += 10 Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

78

Arithme)c Operators
PowerShell follows the same rules as Arithme)c where the other of precedence is as follows:
( ) Parenthesis. - Transforming Nega)ve Numbers. *, / and % Mul)plica)on, division and modulus. + and - Addi)on and subtrac)on.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

79

Comparison Operators
Operator -eq -ne -gt -lt -le -ge Equal to Not Equal to Greater than Less than Less or Equal to Greater or Equal to Descrip+on

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

80

Comparison Operators
Operator Descrip+on

-contains Collec)on of element contains a specic element. -notcontains

-in -no)n

A specic element is present in a collec)on of elements.

-like -notlike

Wildcard string comparison

-match

Matches a regular expression

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

81

Comparison Operators
In PowerShell comparisons are not case sensi)ve for string comparison
PS >"hello" -eq "HELLO" True

To make a comparison be case sensi)ve one only need to add a c to the comparison.
PS >"hello" -ceq "HELLO" False

PowerShell will try to convert the types of the element for evalua)on by analyzing them.
PS >1 -eq "1" True

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

82

Comparison Operators
Many )mes -contains and -in operators are used by mistake to search in strings, this is a common mistake. Their use is for Arrays or Hash lists
PS >"a","b","c" -contains "b" True PS >"b" -in "a","b","c" True

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

83

Boolean Operators
Operator Descrip+on

-and

Return True if all sub-expressions are True

-or

Return True if any sub-expression is True

-not

Return the opposite

-xor

Return True if one sub-expression is True, but not if both are True

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

84

Boolean Operators
Boolean Operators are used to combine several comparison subexpressions. Subexpressions can be parenthe)cal or cmdlets that return a boolean.
PS C:\> ((1 -eq 1) -or (15 -gt 20)) -and ("runnung" -like "*run*") True

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

85

Type Operators
Operator Descrip+on

-is

Return True when an input is of the specied .Net type

-isnot

Return False when an input is of the specied .Net type

-as

Converts the input to a specied type

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

86

Type Operators
Type operators are mostly used to make sure the proper type is used in scripts
C:\PS> (get-date) -is [datetime] True C:\PS> (get-date) -isnot [datetime] False C:\PS> "9/28/12" -as [datetime] Friday, September 28, 2012 12:00:00 AM

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

87

Filtering Objects
For ltering objects PowerShell the Where-Object cmdlet is used since it allows to lter by property value. On PowerShell v2 this is done with a Script Block
Get-Service | where-object { $_.Status -eq "Running" }

On PowerShell v3 this can be done with a Script Block or by Specifying the property and value as parameters.
Get-Service | Where-Object -Property Status -eq -Value Running Get-Service | Where-Object Status -eq Running Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

88

Selec)ng Objects
The Select-Object cmdlet allows for:
Selec)ng specic objects or a Range of objects from an ordered list objects. Selec)ng a given number from the beginning or end of a ordered list of objects. Select specic proper)es from objects. Create a new object proper)es Rename object proper)es

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

89

Selec)ng Objects
Selec)ng specic Objects from a list
PS >Get-Process | Sort-Object workingset -Descending | SelectObject -Index 0,1,2,3,4

Selec)ng a range of objects from a list


PS >Get-Process | Sort-Object workingset -Descending | SelectObject -Index (0..4)

Select the rst 5 from a list


PS >Get-Process | Sort-Object workingset -Descending | SelectObject -first 5

Crea)ng/Renaming a property
PS >Get-Process | Select-Object -Property name,@{name='PID';expression={$_.id}} Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

90

Itera)ng Objects
Itera)on is the method by which several objects in a collec)on are processed one by one and ac)ons are taken against them. In PowerShell there are 2 methods for itera)ng thru objects and are o.en confused:
ForeEach-Object cmdlet and its aliases foreach and %. foreach(<variable> in <collec+on>){} statement.

Each method will take a collec)on a collec)on and process the objects in a ScriptBlock but each behaves dierently and it use will vary case by case.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

91

Itera)ng Objects
The ForEach-Object cdmlet takes a stream of objects from the pipeline and processes each. Uses less memory do to garbage control as objects gets processed as they are passed thru the pipeline. The cmdlet takes 4 main parameters:
Begin <ScriptBlock> Script block executed before processing all objects Process <ScriptBlock> Script block executed per each object being processed End <ScriptBlock> Script block to be executed a.er all objects have been processing all objects. InputObject <PSObject> Object to take ac)ons against. Typically this is taken thru the pipeline.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

92

Itera)ng Objects
The ScriptBlocks parameters are also posi)onal
PS C:\> 1..5 | ForEach-Object { $Sum = 0 } { $Sum += $_ } { $Sum } 15

To skip to the next object to be process in ForEach-Object the keyword return is used. For exi)ng the loop inside of a ForEach-Object the break keyword is used.
C:\PS> $Numbers = 4..7 C:\PS> 1..10 | foreach-object { if ($Numbers -contains $_) { continue }; $_ } 1 2 3 C:\PS> Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

93

Itera)ng Objects
The foreach(<variable> in <collec+on>){} statement places on each itera)on an element of a collec)on loaded in to memory and processes each. Since the collec)on being worked on is loaded in to memory it tends to be faster than the ForEach-Object cmdlet. To skip to the next object to be process in foreach statement the keyword con+nue is used. For exi)ng the loop inside of a foreach statement the break keyword is used.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

94

Itera)ng Objects
The foreach statement has a special variable called $foreach with 2 special methods that can be used:
$foreach.MoveNetx() to skip to the next element in the collec)on and con)nue to process the next element in the collec)on. Returns a Boolean true value that should be handled. $foreach.Current to represent the current element being processed
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

95

Itera)ng Objects
The foreach statement can be used in the shell as well as in scripts
PS >foreach ($i in (1..10)){ >> if ($i -gt 5){ >> continue >> } >> $i >> } >> 1 2 3 4 5

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

96

PowerShell Security

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

97

PowerShell Security
Iden)ty - Is the script created and signed by a developer I trust and/or a signed with a cer)cate from a Cer)cate Authority I trust. Integrity - Scripts can not be modied by malware or malicious user. Control of Execu)on - Control the level of trust for execu)ng scripts. Command Highjack - Prevent injec)on of commands in my path.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

98

Execu)on Policy
Restricted - No Script either local, remote or downloaded can be executed on the system. AllSigned - All script that are ran require to be digitally signed. RemoteSigned - All remote scripts (UNC) or downloaded need to be signed. Unrestricted - No signature for any type of script is required.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

99

PowerShell Prole
Paths for PowerShell Prole:
%windir%\system32\WindowsPowerShell\v1.0\profile.ps1 - Applies

to all local shells and all users.


%windir%\system32\WindowsPowerShell \v1.0\Microsoft.PowerShell_profile.ps1 - Applies to all shells

and all users.


%UserProfile%\My Documents\WindowsPowerShell\profile.ps1 -

Applies to current user user shells on the local host.


%UserProfile%\My Documents\WindowsPowerShell \Microsoft.PowerShell_profile.ps1 - Applies to local user shell

and all shells created by the user on all hosts.


Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

100

PowerShell Prole
Paths for PowerShell ISE Prole:
%windir%\system32\WindowsPowerShell \v1.0\Microsoft.PowerShellISE_profile.ps1 - Applies to all

local ISE Shells and all users.


%UserProfile%\Documents\WindowsPowerShell\ Microsoft.PowerShellISE_profile.ps1 - Applies to current

user user ISE shells on the local host.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

101

Error Handling

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

102

Erros
PowerShell can handle errors directly from the cmdlet, Scrip Error handling or thru senngs in the shell congura)on. PowerShell has 2 types of errors:
Termina)ng Errors - Stops the execu)on of the command chain or script. Non-Termina)ng Errors - Error does not stop the execu)on of the command chain or script.
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

103

Errors
Termina)ng errors happen when:
Syntax error on a script of syntax error when invoking a cmdlet. Cmdlet with the parameter -ErrorAc+on set with a value of Stop Script using the Thow Keyword to invoke a termina)ng Error.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

104

Errors
Non-Termina)ng errors happen when:
Script uses the Write-Error cmdlet to display and log an error. Cmdlet with the parameter -ErrorAc+on set with a value of Con+nue, Ignore or SilentlyCon+nue An excep)on is throws when a call is made to a member of a .Net object. Use of the Trap Keyword in a script.

Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012


Tuesday, November 20, 12

105

Errors
Error Variables for PowerShell are:
$? Execu)on status of the last PS Specic opera)on. $true if the opera)on ran without any errors $false if errors where encountered during the opera)on. $LASTEXITCODE - The exit code for the last Windows executable ran in the current session. $Error - Array containing the errors that have occured in the current session. $MaximumErrorCount - The maximum size for the $Error list (256-32768) $ErrorAc+onPreference - Inuences the handling of Non-Termina)ngErrors. Default to Con+nue. $ErrorView - Species the view of Errors. NormalView shows several lines of informa)on and CategoryView to get single line error messages displayed. Full details s)ll saved to $Error
Introduc)on to Microso. PowerShell for Security Professionals DerbyCon 2012
Tuesday, November 20, 12

106

You might also like