Table of Contents


Introduction

Windows Powershell is a Windows command-line shell designed especially for system administrators. Windows Powershell includes an interactive prompt and a scripting environment that can be used independently or in combination.
Below is a compilation of basics of Powershell Scripting. Hope you enjoy it!

Commands (Aliases)

  • Get-Alias
  • Some of the aliases:
    • Get-Location : pwd
    • Get-ChildItem : ls
    • Get-Process : ps

Commandlets

  • Get-Help
    • Get-Help * | more
    • Get-Help *alias | more
    • Get-Help Get-Command -Parameter * | more : Show parameters allowed for Get-Command cmdlet
  • To update the help system: Update-Help

  • Get-Command
    • Get-Help Get-Command -full | more : Show full help for Get-Command cmdlet, which displays parameters it takes
    • Get-Command -CommandType Cmdlet | more : Display all cmdlets
    • Get-Command -CommandType Cmdlet -Name *process* : Display all cmdlets which have name as process
  • Get-Process : Display Running processes
    • Get-Process -Name notepad : Display process details of all running notepad processes
PS C:\Users\hkh4cks> get-process -Name notepad
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     80       8     1376       9536   101     0.06   2316 notepad
  • Get-Service : Display Services available and their status (Running/Stopped)
PS C:\Users\hkh4cks> Get-Command -CommandType Cmdlet | Measure-Object


Count    : 434
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Note: Cmdlets follow Verb-Noun Relation. So to list Cmdlets that stop something, we would do:

PS C:\Users\hkh4cks> Get-Command -Verb stop

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Function        Stop-DscConfiguration                              PSDesiredStateConfiguration
Function        Stop-Dtc                                           MsDtc
Function        Stop-DtcTransactionsTraceSession                   MsDtc
Function        Stop-NetEventSession                               NetEventPacketCapture
Function        Stop-PcsvDevice                                    PcsvDevice
Function        Stop-ScheduledTask                                 ScheduledTasks
Function        Stop-StorageDiagnosticLog                          Storage
Function        Stop-Trace                                         PSDiagnostics
Cmdlet          Stop-Computer                                      Microsoft.PowerShell.Management
Cmdlet          Stop-DtcDiagnosticResourceManager                  MsDtc
Cmdlet          Stop-Job                                           Microsoft.PowerShell.Core
Cmdlet          Stop-Process                                       Microsoft.PowerShell.Management
Cmdlet          Stop-Service                                       Microsoft.PowerShell.Management
Cmdlet          Stop-Transcript                                    Microsoft.PowerShell.Host
  • Start-Process notepad : Starts notepad process and opens notepad.
  • Stop-Process
    • Stop-Process -Name notepad : Stops notepad process by name.
    • Stop-Process -id <id> -confirm -passthru : Confirm before stopping the process
    • Get-Help Stop-Process -Examples : Give examples of how to stop processes
  • List hostfixes: Get-Hotfix
  • Help about core cmdlets: Get-Help about_Core_Commands
  • Output Formatting
PS C:\Users\hkh4cks> Get-Command -CommandType Cmdlet -Name Format*

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Format-Custom                                      Microsoft.PowerShell.Utility
Cmdlet          Format-List                                        Microsoft.PowerShell.Utility
Cmdlet          Format-SecureBootUEFI                              SecureBoot
Cmdlet          Format-Table                                       Microsoft.PowerShell.Utility
Cmdlet          Format-Wide                                        Microsoft.PowerShell.Utility

PS C:\Users\hkh4cks> Get-Command -CommandType Cmdlet -Name Out*

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Out-Default                                        Microsoft.PowerShell.Core
Cmdlet          Out-File                                           Microsoft.PowerShell.Utility
Cmdlet          Out-GridView                                       Microsoft.PowerShell.Utility
Cmdlet          Out-Host                                           Microsoft.PowerShell.Core
Cmdlet          Out-Null                                           Microsoft.PowerShell.Core
Cmdlet          Out-Printer                                        Microsoft.PowerShell.Utility
Cmdlet          Out-String                                         Microsoft.PowerShell.Utility

Operators

  • Arithmetic : +, -, *, /, %
  • Assignment : =, +=, -=, *=, /=, %=
  • Comparison : -eq, -ne, -gt, -lt, -le, -ge, -match, -nomatch, -replace, -like, -nolike, -in, -notin, -contains, -notcontains
  • Logical : -and, -or, -xor, -not, !
  • Split and Join : -split, -join
PS C:\Users\hkh4cks> "Welcome to PowerShell Penetration Testers" -split " "
Welcome
to
PowerShell
Penetration
Testers

PS C:\Users\hkh4cks> "Wel","Please" -join "come"
WelcomePlease
PS C:\Users\hkh4cks> "Welcome","Please" -join " "
Welcome Please
  • Type Operators : -is, -isnot, -as
  • Redirection: >, », 2>, 2>&1
  • Get-Help about_operators : Help about operators

Strings

  • Here Strings
PS C:\Users\hkh4cks> @"
>> Hello
>> World.
>> This is
>> multiline
>> string
>> "@
>>
Hello
World.
This is
multiline
string

Type Conversions

  • [] : Cast Operator
PS C:\Users\hkh4cks> $val = 2.5 + 5
PS C:\Users\hkh4cks> $val
7.5
PS C:\Users\hkh4cks> $val.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Double                                   System.ValueType


PS C:\Users\hkh4cks> [int]$val
8
PS C:\Users\hkh4cks> [int]$val = 2.5 + 5
PS C:\Users\hkh4cks> $val.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

Arrays

  • Can have multiple types in single array
PS C:\Users\hkh4cks> $arr = 1,2,3
PS C:\Users\hkh4cks> $arr
1
2
3
PS C:\Users\hkh4cks> $arr.Length
3
PS C:\Users\hkh4cks> $arr[0]
1
PS C:\Users\hkh4cks> $arr[1]
2
PS C:\Users\hkh4cks> $arr[2]
3
PS C:\Users\hkh4cks> $arr = 1,"Hi",2.3
PS C:\Users\hkh4cks> $arr
1
Hi
2.3
PS C:\Users\hkh4cks> $arr.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
  • Empty Array
    PS C:\Users\hkh4cks> $emptyArr = @()
    

Conditional statements

  • if, elseif, else
PS C:\Users\hkh4cks> if ( (Get-Process).Count -gt 30 ) {"To many processes"} else {"OK"}
To many processes
  • switch
PS C:\Users\hkh4cks> $val=1
PS C:\Users\hkh4cks> switch ($val) { 1 {"One"} 2 {"Two"} default {"Default"}}
One
PS C:\Users\hkh4cks> $val=20
PS C:\Users\hkh4cks> switch ($val) { 1 {"One"} 2 {"Two"} default {"Default"}}
Default
PS C:\Users\hkh4cks> switch -wildcard ('abc') { a* {"A"} *b* {"B"} c* {"C"} }
A
B

Loop statements

  • while() {}
  • do {} while ()
  • do {} until ()
  • for (;;) {}
  • foreach (in) {}
PS C:\Users\hkh4cks> foreach ($proc in $procs) {
>> $proc.Name
>> }
>>
conhost
csrss
csrss
dasHost
dllhost
dwm
explorer
Idle
  • Loop Cmdlets
    • ForEach-Object
PS C:\Users\hkh4cks> Get-Process | ForEach-Object {$_.Name}
conhost
csrss
csrss
dasHost
dllhost
dwm
explorer
Idle
lsass
MsMpEng
powershell
  • Where-Object
PS C:\Users\hkh4cks> Get-Service | Where-Object {$_.Status -eq "Stopped"}

Status   Name               DisplayName
------   ----               -----------
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service
Stopped  AppIDSvc           Application Identity
  • Assignment
    • Iterate through the processes running on your computer and print the path of the executable for each process
PS C:\Users\hkh4cks> Get-Process | ForEach-Object {$_.Path}
C:\Windows\system32\conhost.exe
C:\Windows\Explorer.EXE
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
C:\Windows\system32\taskhostex.exe
C:\Windows\System32\VBoxTray.exe

Powershell scripting

  • Execution Policy
    • The execution policy is not a security system that restricts user actions.
    • Get-ExecutionPolicy : Display Execution Policy
    • Set-ExecutionPolicy <Policy>: Set Execution Policy
PS C:\Users\hkh4cks\Documents> Get-ExecutionPolicy
Restricted

Functions

  • Using args
PS C:\Users\hkh4cks> function with_param {$args[0] + $args[1]}
PS C:\Users\hkh4cks> with_param 3 7
10
  • Declaring Parameters
PS C:\Users\hkh4cks> function param_mul ($num1, $num2) { $num1 * $num2 }
PS C:\Users\hkh4cks> param_mul 5 2
10
  • Using named parameters
PS C:\Users\hkh4cks> function param_mul ($num1, $num2) { $num1 * $num2 }
PS C:\Users\hkh4cks> param_mul -num2 2 -num1 5
10
  • Dynamic number of parameters: $args is used for dynamic number of parameters
PS C:\Users\hkh4cks> function variable_param ($a,$b) {
>> $a
>> $b
>> $args
>> }
>>
PS C:\Users\hkh4cks> variable_param "Hey" "Hi" "Hello" "World"
Hey
Hi
Hello
World
  • Default Values
PS C:\Users\hkh4cks> function defVal ($a=30) { $a }
PS C:\Users\hkh4cks> defVal
30
PS C:\Users\hkh4cks> defVal 50
50
  • Switch parameters
PS C:\Users\hkh4cks> function switchable ($a, $b, [switch]$flip) {
>> $a + $b
>> if ($flip) { $a - $b }
>> }
>>
PS C:\Users\hkh4cks> switchable 1 2
3
PS C:\Users\hkh4cks> switchable 1 2 -flip 3
3
-1
  • ls function: To view functions available

Advanced Functions

  • param statement
  • Parameter Attributes
    • Mandatory
    • ParameterSetname
    • Position
    • ValueFromPipeline
  • Parameter Validation
    • AllowEmptyString , AllowNull , AllowEmptyCollection
    • ValidateLength , ValidatePattern , ValidateSet
  • Get-Help about_Functions_Advanced_Parameters

Advanced Scripting

  • Dot sourcing
  • CmdletBinding
    • Verbose Output
    • Parameter Checks
    • SupportsShouldProcess (-WhatIf and -Confirm)

Modules

  • Listing Modules : Get-Module -ListAvailable -All
  • Loading/Importing Modules : Import-Module <module>
    • PSModulePath : $env:PSModulePath
  • Unloading/Removing Modules : Remove-Module <module>
  • Different types of Modules
    • Script Modules
    • Manifest Modules
    • Binary Modules
  • Extension for modules is .psm1
  • To view commands available in a module: Get-Command -Module <Module Name>
  • Export-ModuleMember -Function <function names>: Whitelist Functions from a module to be exported.

Manifest Modules

  • Create a Manifest
    • New-ModuleManifest <name>.psd1 : Create new Module Manifest
    • Test-ModuleManifest <name>.psd1: Test Module Manifest
  • Use a Manifest Module

Remoting

  • Based on WSMAN Protocol and uses WinRM
    • Need ports 5985(HTTP) and 5986(HTTPS)
  • Get-Help *remot*
  • Get-Command -CommandType Cmdlet -ParameterName ComputerName
  • Get Cmdlets that have “ComputerName” and “Credential” parameters but not “Session” parameter
Get-Command -CommandType Cmdlet | Where-Object {$_.Parameters.Keys -contains "ComputerName" -and $_.Parameters.Keys -contains "Credential" -and $_.Parameters.Keys -notcontains "Session"}
  • Set-Item WSMan:\localhost\Client\TrustedHosts -Value *: Configure this on attacker machine if you are not in Administrator group.
Invoke-Command

A very important Cmdlet to execute any command on remote machine.

  • Interactive Session - PSSession
    • Runs in a new process (wsmprovhost)
    • Is Stateful
  • Using PSSessions
    • Initiating
    • Interacting
    • Closing
  • Commands
    • New-PSSession
    • Get-PSSession
    • Enter-PSSession
    • PsExec
    • Remove-PSSession
PS C:\Windows\system32> New-PSSession -ComputerName $env:COMPUTERNAME -Credential $(Get-Credential)

 Id Name            ComputerName    State         ConfigurationName     Availability
 -- ----            ------------    -----         -----------------     ------------
 2 Session2        HKH4CKS_WINDOWS Opened        Microsoft.PowerShell     Available

 PS C:\Windows\system32> Get-PSSession

 Id Name            ComputerName    State         ConfigurationName     Availability
 -- ----            ------------    -----         -----------------     ------------
  2 Session2        HKH4CKS_WINDOWS Opened        Microsoft.PowerShell     Available

 PS C:\Windows\system32> Enter-PSSession -Id 2
[HKH4CKS_WINDOWS]: PS C:\Users\hkh4cks\Documents>

Shortcuts

  • Copy: Select the text, then either Right Click or Enter Key
  • Paste: Right Click
  • Delete entire line: Esc Key
  • Delete characters after cursor: Ctrl + End key

Misc

  • Version: $PSVersionTable
  • Download: Invoke-WebReqeust
  • Get Members of any cmdlets: Get-Command -CommandType Cmdlet | Get-Member

Source for Powershell keyboard Shortcuts

Share the fun!