Important PowerShell Commands for Cybersecurity Analysts

The basics of PowerShell commands useful for any Cybersecurity professional.

What You’ll Be Learning

PowerShell is a command-line interface and scripting language for task automation and configuration management. In this article, you will learn the basics of PowerShell along with the commands useful for any Cybersecurity professional.

Table of Contents

Basic PowerShell commands and uses

Let’s begin by reviewing some fundamental PowerShell commands and use cases. These commands are the building blocks to create scripts that will help automate and review security-related tasks.

(back to table of contents)

Get-Help

To get help or more details for the particular command, you can use the Get-Help cmdlet with the command that you need help with. For example, if we run the following:

Get- Help Get-Process

We will get additional help on a specific command.

You can view a list of all available help topics by typing Get-Help.

(back to top of section)

Cmdlets

We just mentioned cmdlets, but what are they? cmdlets are small, lightweight PowerShell modules designed to run tasks in place of traditional commands. Cmdlets will return an output as an object (or an array of objects) which also allows you to transfer this data to other cmdlets using pipes.

Cmdlets always contain a verb and a noun separated by a dash. (For Example: Get-DnsServer or Remove-ADGroup.

Examples of verbs you might see are:

Get: get something Set: define something Start: run something Stop: stop something New: create something

(back to top of section)

Pipe

A pipe character | is used to pass data from one cmdlet to another. For example, pipes can be used to sort the output of one cmdlet and redirect that output to a file. Multiple pipes can be used in tandem to build more complex actions!

For example, to create a list of running processes on your machine, and save it to a file, we would use the command below:

Get-Process | Out-File c:\PS\powershell.txt

Learn more in the Out-File docs.

(back to top of section)

Using PowerShell to traverse directories

Commands for changing directories and viewing directory listings are the same as the Linux command line and Windows command prompt. Commands such as cd, dir, mkdir,ls, type, etc will still work.

Learn more in the Managing Current Location docs.

(back to top of section)

Aliases

Aliases in PowerShell provide an alternative name for running a cmdlet. There are several shorthand aliases built-in. For example, the ls command will generate the same results as Get-ChildItem.

PS C\User\U1D256> ls
Directory: C\User\U1D256>
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 11/5/2021 10:37AM .vscode
d-r--- 11/16/2021 8:00AM .Documents
d-r--- 12/17/2021 10:02AM .Downloads
PS C\User\U1D256> Get-ChildItem
Directory: C\User\U1D256>
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 11/5/2021 10:37AM .vscode
d-r--- 11/16/2021 8:00AM .Documents
d-r--- 12/17/2021 10:02AM .Downloads

All aliases can be viewed by running the alias command, and specific aliases can be viewed by specifying them; for example, alias cd. In the screenshot below we see that the alias for cd is Set-Location.

PS C\User\U1D256> alias cd
Command Type Name Version Source
------------ ---- ------- ------
Alias cd -> Set-Location

(back to top of section)

Files in PowerShell

In this section, we will learn how to:

  • Read a file using the Get-Content.
  • Create a new file using the Set-Content command.

(back to table of contents)

Reading from a file

Similar to the cat command in Linux, we can use the Get-Content cmdlet in PowerShell to read the contents of a file. When Get-Content is run, the contents of the file are read and the result can be stored in a variable for later use or displayed on the screen.

For example, we can use the command Get-Content /PS/Names.txt to read the file Names which is saved on a local C Drive in a folder named PS.

PS C:\> Get-Content /PS/Names.txt
Liam Johnson
Olivia Pope
Noah Clark
Emma Michaelson
Oliver Washington
Ava Miller
Elijah Williams
Charlotte Smith
Mohammed White
Jaris Rodriguez

Note: By adding the -TotalCount argument, we can specify how many lines we would like PowerShell to read from the top.

Get-Content <PATH> -TotalCount 5

Adding -TotalCount 5 shows the top five items in the names.txt file.

PS C:\> Get-Content -TotalCount 5 /PS/Names.txt
Liam Johnson
Olivia Pope
Noah Clark
Emma Michaelson
Oliver Washington

The -Tail argument will do the same but read from the bottom of the file.

(back to top of section)

Writing content to a file

In addition to reading files, it is possible to write data to files, either by using the Set-Content command to create and overwrite files or the Add-Content command to append content to an existing file.

PS C:\> Set-Content - Value "Rachel Rose" -Path /PS/Names.txt
PS C:\> Get-Content /PS/Names.txt
Rachel Rose
PS C:\>

(back to top of section)

Commands to manipulate files

In this section, you will learn how to use PowerShell to manipulate files.

(back to table of contents)

Convert-To

Structured data types can be converted into different formats using PowerShell cmdlets; for example, from .txt to .csv. Some common ConvertTo commands in PowerShell are:

  • ConvertTo-Csv
  • ConvertTo-Html
  • ConvertTo-Json
  • ConvertTo-Xml

Here are some additional Reading on Convert commands

(back to top of section)

Convert-From

Alternatively, the Convert-From command creates objects from different formats using variable-length strings that are generated by the ConvertTo cmdlets. Some common Convert-From commands in PowerShell are:

  • ConvertFrom-Csv
  • ConvertFrom-Json
  • ConvertFrom-Markdown
  • `ConvertFrom-StringData

For example, the ConvertTo-Json cmdlet allows you to convert an object into a JSON-formatted string. The properties are converted to field names, the field values are converted to property values, and the methods are removed.

PS C:\Users> Get-Date
Thursday, December 30, 2021, 8:16:10 AM
PS C:\Users> Get-Date | ConverTo-Json
{
"value": "\/Date(1640870187485)\/",
"DisplayHint": 2,
"DateTime": "Thursday, December 30, 2021, 8:16:27 AM"
}
PS C:\Users> Get-Date | ConverTo-Json | ConvertFrom-Json
value DisplayHint DateTime
----- ----------- --------
12/30/2021 1:16:41 PM 2 Thursday, December 30, 2021, 8:16:41 AM

(back to top of section)

Creating files and folders

We create items in PowerShell using the New-Item command.

Example: This command creates the new folder C:\temp\Test Folder

New-Item -Path 'C:\temp\Test Folder' -ItemType Directory

Example: This command creates the new empty file C:\temp\New Folder\file.txt

New-Item -Path 'C:\temp\Test Folder\file.txt' -ItemType File

(back to top of section)

Commands to import and remove modules in PowerShell

In this section, you will learn how to use PowerShell Modules. Modules provide the capability to group like functions together. There are a number of built-in modules and additional modules can be installed or will appear on top of other modules.

In PowerShell, a module is considered a package that contains various functions, workflows, and variables that can operate as a small program.

For additional information, check out the Microsoft Documentation on modules.

(back to table of contents)

The PowerShell Gallery is a repository for sharing useful PowerShell scripts and modules, some items are created by Microsoft and some are created by the PowerShell community.

Browse the PowerShell Gallery for modules you’ll want to install here.

(back to top of section)

Viewing modules

Using the Get-Module cmdlet will list currently loaded modules on a computer. Using the -ListAvailable option with this command will also allow you to view all modules that are available for use but not yet imported on the computer.

The -ListAvailable option can also be used when a specific module has been provided to list all the available functions for that module.

(back to top of section)

Importing modules

Modules need to be imported to your local PowerShell session before the cmdlets and functions from that module can be used. Modules can be loaded into the current PowerShell session by using the Import-Module cmdlet and specifying the module either by name (-Name) or by path (-Path).

Example: If you needed to import the PKI PowerShell module, which is used in digital certificates to protect sensitive public key infrastructure data, you would use this comment:

Import-Module -Name PKI

(back to top of section)

Installing modules

If a module is not listed as available, then the module can be installed from a repository, such as the PowerShell Gallery, or from another repository using the -InstallModule cmdlet.

(back to top of section)

Removing modules

When you need to remove a module, the commands that the module added are deleted from the session. This is useful when creating your own modules as you may need to remove and re-import a module when you make changes to it.

Example: We would remove the PKI module using the command:

Remove-Module -Name PKI

(back to top of section)

Commands for daily security tasks

In this section, you will learn some of the most common PowerShell security commands that are used by every Cybersecurity professional today. You should be familiar with these common commands used for troubleshooting well-known cyberattacks in the industry today.

(back to table of contents)

Get-ExecutionPolicy and Set-ExecutionPolicy

You can create and execute PowerShell scripts, however, Microsoft has disabled scripting by default in an effort to prevent malicious code from executing in a PowerShell environment. You can use the Get-ExecutionPolicy to check which execution policy is enforced prior to running a script and then use the Set-ExecutionPolicy command to change the level of security if needed.

There are four levels of security associated with the Set-ExecutionPolicy command:

  • Unrestricted: This removes all restrictions from the execution policy.
  • Restricted: This is the default execution policy and only allows commands to be entered interactively. PowerShell scripts are not allowed to run.
  • All Signed: If the execution policy is set to All Signed, scripts will be allowed to run if they are signed by a trusted publisher.
  • Remote Signed: If the execution policy is set to Remote Signed, PowerShell scripts that have been created locally will be allowed to run. Scripts created remotely will be allowed to run if they are signed by a trusted publisher.

(back to top of section)

Get-Service

This command provides a list of every service that is currently installed on your system.

If you suspect a particular service is worth checking out for security reasons, we can append the –Name argument, and this will allow you to see the state of the service on the machine.

PS C:\Users\U1D256> Get-Service
Status Name Display Name
------ ---- ------------
Running BFE Base Filtering System
Stopped BITS Background Intelligent Transfer Ser...
Running camsvc Capability Access Manager Service
...

(back to top of section)

Get-Process

Unlike the Get-Service command in PowerShell, which displays a list of the different system services, the Get-Process command can display a list of every process the system currently runs. This command can also be used to query processes running on a remote machine or server.

PS C:\Users\U1D256> Get-Process
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
3071 138 359840 354688 25248 0 A180AG
1001 52 52820 65824 1,557.13 8732 1 A180RS
...

(back to top of section)

Stop-Process

This is the complementary command to Get-Process. If you suspect that a malicious or unwanted process is running on your local machine or remote server, running Stop-Process -Name or Stop-Process -Id will terminate the running process.

For example, if you wanted to find the owner of a running process on a machine, try this script:

PS C:\Users\U1D256> Get-Process pwsh -IncludeUserName
Handles WS(K) CPU(s) Id UserName ProcessName
------- ----- ------ -- -------- -----------
782 132080 2.08 2188 DOMAIN01\user01 pwsh

(back to top of section)

Get-EventLog

Being able to read logs from the local machine is important. Event logs are an important part of fault diagnosis or incident response.

PowerShell can be used to parse your computer’s event logs using the Get-EventLog command. By default, it will query the local machine; however, it can also be used to query logs from remote connections.

For additional reading, check out the Microsoft document on Get-EventLog.

(back to top of section)

Get-ADUser

The Get-ADUser cmdlet gets a specified user object or performs a search to get multiple user objects. This cmdlet retrieves a default set of user object properties. To retrieve additional properties use the -Properties parameter.

Security teams such as Identity Access Management Teams and Identity Governance Teams heavily leverage this command.

Example: This command gets all of the properties of the user with the SAM account name Nicole Scott.

PS C:\Users\U1D256>Get-ADUser -Identity NicoleScott -Properties *
Surname : Scott
Name : Nicole Scott
UserPrincipalName :
GivenName : Nicole
Enabled : False
SamAccountName : NicoleScott
ObjectClass : user
SID : S-1-5-21-2889043008-4136710315-2444824263-3544
ObjectGUID : e1418d64-096c-4cb0-b903-ebb66562d99d
DistinguishedName : CN=Nicole Scott,OU=NorthAmerica,OU=Sales,OU=UserAccounts,DC=FABRIKAM,DC=COM

(back to top of section)

DNS lookups

DNS attacks remain one of the top attacks that Cybersecurity professionals will have to troubleshoot today. The DNS service is a well known attack vector for hackers today.

We can look up the DNS entry for a host using the command:

Resolve-DnsName -Name "Hostname"

By appending the -server switch, followed by a DNS server’s IP address, we can perform a DNS resolve request against a specific server to verify resolution is working properly.

The Get-DnsClient cmdlet lets you check the DNS client information for a device. It indicates what DNS servers are being used by the device to perform address resolutions as configured on multiple adapters.

The Set-DnsClientServerAddress cmdlet allows for specified DNS servers to be added to the network configuration.

Here are some additional DNS PowerShell Commands

(back to top of section)

Ping devices locally or remotely

The Test-NetConnection cmdlet allows us to test network connectivity on the LAN and WAN.

For example, the command Test-NetConnection -ComputerName "Hostname or IP" performs a ping which determines if network connectivity between the local device and the target computer or domain exists.

This is a useful command for a security professional executing a DDoS attack.

(back to top of section)

Get-NetIPConfiguration

The Get-NetIPConfiguration cmdlet gets network configurations, including usable interfaces, IP addresses, and DNS servers. This is helpful for any cybersecurity professional who needs to troubleshoot and identify any rogue IP addresses on the network.

(back to top of section)

Testing network connection

The Test-NetConnection cmdlet shows diagnostic information for a connection. It supports ping tests, TCP tests, route tracing, and route selection diagnostics. Depending on the parameters, the output can include the DNS lookup results, a list of IP interfaces, IPsec rules, route/source address selection results, and/or confirmation of connection establishment.

Port security attacks are very prevalent today. If we want to verify if a port is open on our machine or server we could run this command:

Test-NetConnection -ComputerName 127.0.0.1 -Port 4000

(back to top of section)

Remote PowerShell commands

Windows PowerShell remoting lets you run any Windows PowerShell command on one or more remote computers. You can establish persistent connections, start interactive sessions, and run scripts on remote computers. The remote computer must be configured for remote management.

Read more about remove PowerShell commands here.

(back to table of contents)

Start a session

To start an interactive session with a single remote computer, use the Enter-PSSession cmdlet. For example, to start an interactive session with the Server01 remote computer, use the following command:

Enter-PSSession Server01

To end the interactive session, use the following command:

Exit-PSSession

(back to top of section)

Run a script

To run a script on remote computers, use the -FilePath parameter from the Invoke-Command cmdlet. The script must be accessible by your local computer. The results are returned to your local computer.

Example: The following command runs the GetActiveAccounts.ps1 script on the remote computers, Server11, and Server12.

Invoke-Command -ComputerName Server11, Server12 -FilePath c:\Scripts\GetActiveAccounts.ps1

(back to top of section)

Conclusion

In this article, we reviewed some of the most important PowerShell commands and applicable use cases. Creating PowerShell scripts and running commands are a powerful way to automate daily security analyst tasks. You should continue to research and practice working with PowerShell to improve your skillset.

(back to table of contents)

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team