Powershell Basics

Powershell is the Windows Scripting Language and shell environment that is built using the .NET framework.

  • allows Powershell to execute .NET functions directly from its shell,
  • the output of these cmdlets are objects – making Powershell somewhat object oriented —> This also means that running cmdlets allows you to perform actions on the output object(which makes it convenient to pass output from one cmdlet to another).
  • The normal format of a cmdlet is represented using Verb-Noun
    (i.e) #Get-Command

Power Shell – Allowed Verbs

  • Get
  • Start
  • Stop
  • Read
  • Write
  • New
  • Out
  • Set
  • Invoke

Invoke vs. Start

Invoke verb to perform synchronous operations, such as running a command and waiting for it to end. Use the Start verb to begin asynchronous operations, such as starting an autonomous process.

Get-Help <Command-Name> —> To get to know more about that command with examples
Get-Help Test-Connection -examples

Get-Command —> To get the list of cmdlets in the machine & also we can use like
Get-Command *-Noun (or) Verb-*

Pipeline(|)


*Pipeline(|) is used to pass output from one cmdlet to another,.

Command to get the member of each command

Get-Command | Get-Member

example

Get-ExecutionPolicy | Get-Member -MemberType Method ---> Pulling out methods of Get-ExecutionPolicy

Creating Objects From Previous cmdlets

One way of manipulating objects is pulling out the properties from the output of a cmdlet and creating a new object. This is done using the Select-Object _cmdlet_

Get-ChildItem | Seclect-Object -Property Name, Mode---> To get the list of files,.

To list custom entries

Get-ChildItem | Seclect-Object -Property Name, Mode -unique or -first x or last x

Filtering Object

When retrieving output objects, you may want to select objects that match a very specific value. You can do this using the Where-Object to filter based on the value of properties.

Verb-Noun | Where-Object -Property PropertyName -operator Value
Verb-Noun | Where-Object {$_.PropertyName -operator Value}
The second version uses the $_ operator to iterate through every object passed to the Where-Object cmdlet.

Powershell is quite sensitive so make sure you don’t put quotes around the command!

-eq ----> equals to
-gt ----> greater than
-contains ----> contains

Get-Service | Where-Object -Property Status -eq Running ` # It lists running processes alone,.

Sort Object

Verb-Noun | Sort-Object

example

Get-ChildItem | Sort-Object

To search a specific file on the machine

Get-ChildItem

Get-Content .\interesting-file.txt.txt` # Get Contents of the specific file,.

Get-Command | Where-Object -Property CommandType -eq cmdlet ---> To List the whole cmdlet on a system,.

Count of the cmdlet list

$count = Get-Command | Where-Object -Property CommandType -eq cmdlet
$count.count  # it will list the number of entries,. (Counting)

Getting File Hash

Get-FileHash <File Name> -Algorithm MD5 # It will writes the MD5 hash of the file

Getting Current Directory

Get-Location

Test a Path’s Existence

Test-Path "C:\Users\Administrator\Documents\Passwords"

Invoke-WebRequest http://www.facebook.com/login.php # to give Web Request
# Learn more about this command using "Get-Help Invoke-WebRequest -example"

Learn more about this command using “Get-Help Invoke-WebRequest -example”

$folder="C:\Users\Administrator\Desktop\b64.txt"
$content=Get-Content $file
$decoded=[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($content))
$decoded

Get-Service -Name W32Time | Get-Member ----> To get the member of specific service.

Get-Service -Name W32Time | Select-Object -Property * ----> To view the details of a service

(Get-Service -Name w32time).Stop()  # To stop specific service
(Get-Service -Name w32time).method() #Format

Get-Process -Name Powershell  # to get a specific process
Get-Process -Name Powershell.kill() # to kill the specific process

Get-Command -Name *process*

# Setting up Environment Variables

$path = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
$newpath = $path + ';C:\Program Files\Fabrikam\Modules'
[Environment]::SetEnvironmentVariable("PSModulePath", $newpath, 'Machine')

Enumeration with Powershell

The first step when you have gained initial access to any machine would be to enumerate. We’ll be enumerating the following:

users

 Get-LocalUser
 Get-LocalUser -Name duck | select * # Get user's extensive details 
 Get-LocalUser | Where-Object -Property SID -eq S-1-5-21-1394777289-3961777894-1791813945-501 #Command to get SID  of specific user...
 Get-LocalGroup # Get list of local groups
 (Get-LocalGroup).count #Local Group's count

Get-Clipboard  # To display the clipboard

basic networking information

Get-NetIPAddress # To Get the IP address info
Get-NetRoute # To Get route details
Get-NetTCPConnection #netstat equivalent (to find the listening port)

file permissions

 Get-HotFix # to view the list of installed patches
 Get-HotFix KB3176936 | select * # To view the specific patch details

# To find the location of the specific file ob the system

Get-ChildItem -Path C:\ -Include *.bak* -File -Recurse -ErrorAction SilentlyContinue

# To Search the file that contains specific pattern
Get-ChildItem -Path C:\* -Recurse | Select-String -Pattern API_KEY

scheduled and running tasks

New-ScheduledTaskAction -Execute <app.exe> # To execute an application

Get-Acl C:\  # To detect the owner of a path or file 

From Command Prompt

Running Powershell Script at Background

PowerShell.exe -windowstyle hidden .\myscript.ps1

EncodedCommand —> Used to execute Base64 encoded scripts and commands

powershell.exe -EncodedCommand $EncodedCommand

Abbreviations are applicable in powershell

 

powershell.exe -ec $EncodedCommand

comdlet aliases

most of the commandlets have aliases

Get-ChildItem (ls)

# To find aliases for a specific commandlets use below command
Get-Alias -Definition <cmdlet for which we need to know alias>
Get-Alias -Definition Get-ChildItem
Get-Alias -Definition Format-Hex # fhx -> Format-Hex

Get-Alias -Name *  # Lists all the aliases available in powershell
Get-WmiObject #gwmi
Format-List #fl

# To get the detail of specific alias
Get-Command iex | select *
Get-Alias -Definition Export-Csv  # epcsv -> Export-Csv ---> Exporting a result to CSV file.

# To explore registry hives

cd HKLM:\ ---> To explore registry hives

# To explore further
 cd .\<press TAB to get more option> ---> COntinue this until you get the path you need and 
 use ls command to view its child item

Select-String  ---> to search for specific pattern in a file in system,.

sls (or) Select-String -Path <specify path> -Pattern <specify the pattern>

gc (or) Get-Content

% alias for ForEach-Object 

Below variables help to validate the underlying operating system

$IsWindows
$IsLinux
$IsMacOS

$PSVersionTable ---> To know powershell version , build details

Powershell Automatic Variables

Modules

Similar to Python Module, each module contains set of function and cmdlets

# Commands to deal with modules
Module file is usually in .psm1 extention

Get-Module ----> To retrieve the modules
Get-Module -ListAvailable ---> To get the list available

Import-Module <.psm1 file> # Once we import a module all of its cmdlets will be availble to us,.

# For example let's take a module called "PowerSploit"

PowerSploit Download Link

# We can also create our own module

$Env:PSModulePath # To find the module path

Create "PowerSploit" folder in the module path

then, copy the above module file into one of the module path "PowerSploit"

Once did above steps, Open Powershell window 

Import-Module PowerSploit # In Order to import the module

Get-Module # To Verify the imported module

# To Get to know the commands inside the imported module

Get-Command -Module PowerSploit

Scripts

 .\script.ps1 # To execute a PS script
mandatory=$true ---> to be set to bypass giving parameters

ForEach-Object ---> cmdlets can be used to iterate through each element during loop usage

# Aliases for the above comdlets
% -> ForEach-Object
foreach -> ForEach-Object 

# Loop statements in PowerShell
for()
while()
foreach()
do {something} while()
do {something} until()

#Get help for above loops

Get-Help about_while()

Get-ChildItem | Format-List # Allows us to view the file creation time and detailed view of a file
Get-ChildItem | Format- <use ctrl + space > # In order to get the different usable options

Get-ChildItem | Format-List * # Shows ton of information for each object

Powershell is case in-sensitive (caps or small doesn’t matter)

Write-Output  #"echo" quivalent
Get-ChildItem | Out-Null # Linux /dev/null equivalent , used to flush the unwanted outcome
Get-ChildItem | Out-GridView # Shows the output inside a grid
Move-Item --> mv # To move an item
Copy-Item --> cp # To Copy an item
Remove-Item ---> del # To Remove an item

Powershell Profiles

$profile # We may modify the profile too,.
$profile | Select-Object * # Displays the profile location

New-Item -ItemType Directory hello # Creates a directory called "hello"

Get-Help about_Execution_Policies

Variables

$variable = "Hello"
$interger = -10
$integer.<ctrl + space>
$integer.GetType() # To get the type of value
$interger.ToByte() # To convert the value into bytes

GetType() # Can be used to get the type of data ( It is a  method)

Get-TypeData #To view all the data types
Get-TypeData *IP* # Data type of IP already defined

[IPAddress]"256.0.0.1" # Powershell triggers error and says "Hey this isn't valid IP" 
[MailAddress]"perumalgmail.com" # Powershell triggers error and says "Hey this is invalid email address"

PSDrives (Powershell Drives)

Get-PSDrive # lists all the drives available in powershell

# To get into anyone of the drives listed by above commandlet
cd <command>:

cd Variable:
Get-ChildItem # To view all of the chile items that were created so far

$Error # Displays the recent error

$env:windir # To view the environment variable

$loopback =[IPAddress]"127.0.0.1" # To create a varibale that hold loopback address

Enabling Powershell Transcription logging

While you do not have to use these commands for this task, these will turn on PowerShell Transcription Logging for a local host if entered in an Administrator command prompt:

reg add HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\Transcription /v EnableTranscripting /t REG_DWORD /d 0x1 /f
reg add HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\Transcription /v OutputDirectory /t REG_SZ /d C:/ /f
reg add HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\Transcription /v EnableInvocationHeader /t REG_DWORD /d 0x1 /f

net user s4nta grinchstolechristmas /add 
# to add user : s4nta and password:grinchstolechristmas 
cd $env:USERPROFILE/Desktop # To navigate to the current user's desktop folder

Invoke-WebRequest -Uri http://192.168.31.152:4545/paper-1.14.4-245.jar -Outfile paper-1.14.4-245.jar # To download a file through Web-Request, wget replacement.