A command shell for Windows, that provides interactive commands like Command Prompt, but additionally has a powerful scripting environment, that allows users to write scripts on the fly.

It is built on top of .NET and run the majority of the same commands as the Command Prompt.

It utilise lightweight commands called Cmdlets.

There are a couple of Differences between Powershell and CMD, but all commands in CMD will work in PowerShell.

Object

The main difference between PowerShell and other CLIs is that everything is an object.

The data associated with an object is called properties and it’s functions are called methods.

Help

  • Get-Help <command name>: for man-page like offline help in text.
  • Get-Help <command name> -online: for displaying a Microsoft Docs web page for the command.
  • Get-Command: View all commands, functions, Cmdlets, and aliases loaded into current PowerShell session.
  • Get-Module: View all PowerShell Modules loaded into session.
  • Update-Help: ensures that the offline help-pages are up to date.

Command History

Command history is kept in two ways:

  • Built-in session history, which is implemented and deleted at the beginning and end of each console session.
  • Though the RSReadLine module which tracks history commands used in all sessions by the host. Per default it tracks the last 4096 commands but can be changed by setting the $MaximumHistoryCount variable. The history is stored in $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ $($host.Name)_history.txt.

Hotkeys

HotKeyDescription
CTRL+RIt makes for a searchable history. We can start
typing after, and it will show us results that
match previous commands.
CTRL+LQuick screen clear.
CTRL+ALT+Shift+?This will print the entire list of keyboard
shortcuts PowerShell will recognise.
EscapeWhen typing into the CLI, if you wish to clear
the entire line, instead of holding backspace,
you can just hit escape, which will
erase the line.
↑Scroll up through our previous history.
↓Scroll down through our previous history.
F7Brings up a TUI with a scroll-able interactive
history from our session.

It also has tab-completion with tab and SHIFT-tab.

Input/Output Operators

  • <command> > <file>: Redirect output from <command> into <file>. Overwrites the files’ contents.
  • <command> >> <file>: Redirect output from <command> to the end of <file> by appending it without overwriting content.
  • <command> < <file>: Pass content of <file> as input to <command>.
  • <command1> | <command2>: Piping which is redirecting output (text or object) from command1 as input to command2 (from left to right).
  • <command1> & <command2>: Execute both commands in succession regardless of whether the commands succeed or fail.
  • <command1> && <command2>: Execute command1 and only if this completes properly execute command2.
  • <command1> || <command2>: Execute command2 and only if this fails execute command2.

File & Directory Commands

  • Get-Item (gi): Retrieve an object (could be a file, folder, registry object, etc.)
  • Get-ChildItem (ls / dir / gci): Lists out the content of a folder or registry hive.
  • New-Item (md / mkdir / ni): Create new objects. (can be files, folders, symlinks, registry entries and more)
  • new-item -name "Name" -ItemType <directory/file> : Specify the new items name and object type.
  • Set-Item (si): Modify the property values of an object.
  • Copy-Item (copy / cp / ci): Make a duplicate of the item.
  • Rename-Item (ren / rni): Changes the object name.
  • Rename-Item .\Object-1.md -NewName Object-2.md : Rename object-1 to object-2.
  • Remove-Item (rm / del / rmdir): Deletes the object.
  • Get-Content (cat / type): Displays the content within a file or object.
  • Add-Content <file> "Content to add" (ac): Append content to a file.
  • Set-Content (sc): overwrite any content in a file with new data.
  • Clear-Content (clc): Clear the content of the files without deleting the file itself.
  • Compare-Object (diff / compare): Compare two or more objects against each other. This includes the object itself and the content within.

Find & Filter Content

  • Get-Item <item> | get-member: Use Get-Item to select an object and then Get-Member to view the object’s properties.
  • Get-Item <item> | Select-Object -Property *: Select an object and then view its Property values.
  • Get-Item * | Select-Object -Property Name,PasswordLastSet: Select objects and then filter to view specific properties.
  • Get-Item * | Sort-Object -Property Name | Group-Object -property Enabled: Sort and view Objects by a specific property setting.
  • Get-ChildItem -Path C:\Users\MTanaka\ -File -Recurse: List all File objects in the directory specified.
  • Get-ChildItem -Path C:\Users\MTanaka\ -File -Recurse -ErrorAction SilentlyContinue | where $_.Name -like "*.txt": Search for all objects with the ‘.txt’ file extension.
  • Get-ChildItem -Path C:\Users\MTanaka\ -File -Recurse -ErrorAction SilentlyContinue | where $.Name -like "*.txt" -or $.Name -like ".py" -or $_.Name -like ".ps1" -or $.Name -like "*.md" -or $.Name -like "*.csv": Search for objects matching a list of different file extensions.
  • Get-ChildItem -Path C:\Users\MTanaka\ -Filter "*.txt" -Recurse -File | sls "Password","credential","key": Searching for keywords within an object’s content.

User Commands

  • Get-LocalGroup: View all groups specific to the host only.
  • Get-LocalUser: View all local users. Similar to net user.
  • New-LocalUser -Name "username" -NoPassword: Create a new Local user.
  • Set-LocalUser -Name "username" -Password $Password -Description "users description": Modify a local user’s settings.
  • Get-LocalGroupMember -Name "Group_Name": Check Group membership.
  • Add-LocalGroupMember -Group "Group_Name" -Member "User-To-Add": Add a user to a local group.
  • Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability -Online: Install Remote System Administration Tools.
  • Get-Module -Name ActiveDirectory -ListAvailable: Locate the Active Directory module.
  • Get-ADUser -Filter *: List all domain users.
  • Get-ADUser -Identity <name>: Show a specific domain user and its properties.
  • Get-ADUser -Filter {EmailAddress -like '*greenhorn.corp'}: Filter domain users based on the EmailAddress property.
  • New-ADUser -Name "UserName" -Surname "Last_Name" -GivenName "First_Name" -Office "Security" -OtherAttributes @{'title'’Analyst’;‘mail’'UserName@greenhorn.corp'} -Accountpassword (Read-Host -AsSecureString "AccountPassword") -Enabled $true: Create a New Domain user and set its properties such as name, password, and other attributes.
  • Set-ADUser -Identity <UserName> -Description "Information we want in the description field": Modify the property settings of a domain user.

Networking Commands

  • Get-NetIPInterface -ifIndex <#>: Retrieve network adaptor properties of the interface listed as ifIndex #.
  • Get-NetIPAddress: Retrieves the IP configurations of each adaptor. Similar to IPConfig.
  • Get-NetNeighbor: Retrieves the neighbour entries from the cache. Similar to arp -a.
  • Get-Netroute: Will print the current route table. Similar to IPRoute.
  • Set-NetAdapter: Set basic adaptor properties at the Layer-2 level, such as VLAN id, description, and MAC-Address.
  • Set-NetIPInterface: Modifies the settings of an interface to include DHCP status, MTU, and other metrics.
  • Set-NetIPAddress: Modifies the configuration of a network adaptor.
  • Disable-NetAdapter: Used to disable network adaptor interfaces.
  • Enable-NetAdapter: Used to turn network adaptors back on and allow network connections.
  • Restart-NetAdapter: Used to restart an adapter. It can be useful to help push changes made to adapter settings.
  • Test-NetConnection: Allows for diagnostic checks to be run on a connection. It supports ping, tcp, route tracing, and more.
  • Get-WindowsCapability -Online <PIPE> Where-Object Name -like 'OpenSSH*': List Windows packages for OpenSSH.
  • Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0: Install the SSH package to the host.
  • ssh <user>@<ip address>: Basic SSH connect string.
  • ssh-keygen: Generate SSH keys for the user you run the command as. This enables the use of the user for remote login.
  • winrm quickconfig: Enable WinRM.
  • Test-WSMan -ComputerName "10.129.224.248": Test if the host specified has WinRM running.
  • Enter-PSSession -ComputerName 10.129.224.248 -Credential htb-student -Authentication Negotiate: Start a remote PowerShell session with the host specified.

Services

  • Get-service: List all services
  • Get-Service | ft DisplayName,Status: List all services and format their information by DisplayName and Status.
  • Get-Service | where DisplayName -like 'Name' | ft DisplayName,ServiceName,Status: Query for a specific service whose name matches ‘name’.
  • Start-Service <Name>: Start a service by name.
  • Stop-Service <Name>: Stop a service by name.
  • Set-Service -Name <Name> -StartType Disabled: Change settings of the service specified.
  • Get-service -ComputerName ACADEMY-ICL-DC: Remote query of a hosts services.
  • Get-Service -ComputerName ACADEMY-ICL-DC | Where-Object {$_.Status -eq "Running"}: Remote query of services filtered to only show those that are Running.
  • Invoke-Command -ComputerName ACADEMY-ICL-DC,LOCALHOST -ScriptBlock {Get-Service -Name 'windefend'}: Issue the Get-Service command on a list of hosts.

Web-interaction Commands

  • Invoke-WebRequest -Uri "https://website-to-visit" -Method GET: Utilizes Invoke-WebRequest to browse to a website and issue a GET request.
  • Invoke-WebRequest -Uri "https://website-to-visit.html" -Method GET | fl Images: Issues a GET request to the site specified and then pipes the output to format a list of all image files listed in the site.
  • Invoke-WebRequest -Uri "https://website-to-visit\file.ps1" -OutFile "C:<filename>": Downloads a file from the website and writes it to disk with -Outfile.
  • (New-Object Net.WebClient).DownloadFile("https://website-to-visit\tools.zip", "Tools.zip"): Uses the .NET string Net.WebClient to download a file from the URL specified.

Event Log Commands

webutil

  • wevtutil el: Uses the Windows Events Commandline utility to enumerate all log sources.
  • wevtutil gl "name": Will gather config information about the log specified.
  • wevtutil qe <Name> /c:5 /rd:true /f:text: Query a log for events.
  • wevtutil epl <Name> C:\system_export.evtx: Export a Log.

Get-WinEvent

  • Get-WinEvent -ListLog *: List all logging facilities using PowerShell cmdlets.
  • Get-WinEvent -LogName 'Name' -MaxEvents 5 | Select-Object -ExpandProperty Message: View the messages of a specific log.
  • Get-WinEvent -FilterHashTable @{LogName=‘Security’;ID=‘4625 ’} : Query for a specific log by eventID.

Registry Commands

  • Get-Item -Path Registry::<hive>\Path-to-key\ | Select-Object -ExpandProperty Property: See the sub-keys and properties of a registry key.
  • Get-ChildItem -Path <hive>:\Path-to-key -Recurse: Recursively search through a Key and all subkeys.
  • Get-ItemProperty -Path Registry::<hive>\Path-to-key\key: View the properties and values of a specific key.
  • REG QUERY <hive>\PATH\KEY: Use reg.exe to query the registry.
  • REG QUERY <hive> /F "Password" /t REG_SZ /S /K: Search for specific strings within the Registry hive.
  • New-Item -Path <hive>:\PATH\ -Name KeyName: Create a new Registry Key.
  • New-ItemProperty -Path <hive>:\PATH\KEY -Name "ValueName" -PropertyType String -Value "C:\Users\htb-student\Downloads\payload.exe": Set a new Value pair within a registry Key.
  • REG add "<hive>\PATH\KEY" /v access /t REG_SZ /d "C:\Users\htb-student\Downloads\payload.exe": Use Reg.exe to create a new key/value pair.
  • Remove-ItemProperty -Path <hive>:\PATH\KEY -Name "name": Delete a key/value from the registry.