homepage
Open menu
Go one level top
  • Train and Certify
    Train and Certify

    Immediately apply the skills and techniques learned in SANS courses, ranges, and summits

    • Overview
    • Courses
      • Overview
      • Full Course List
      • By Focus Areas
        • Cloud Security
        • Cyber Defense
        • Cybersecurity and IT Essentials
        • DFIR
        • Industrial Control Systems
        • Offensive Operations
        • Management, Legal, and Audit
      • By Skill Levels
        • New to Cyber
        • Essentials
        • Advanced
        • Expert
      • Training Formats
        • OnDemand
        • In-Person
        • Live Online
      • Course Demos
    • Training Roadmaps
      • Skills Roadmap
      • Focus Area Job Roles
        • Cyber Defence Job Roles
        • Offensive Operations Job Roles
        • DFIR Job Roles
        • Cloud Job Roles
        • ICS Job Roles
        • Leadership Job Roles
      • NICE Framework
        • Security Provisionals
        • Operate and Maintain
        • Oversee and Govern
        • Protect and Defend
        • Analyze
        • Collect and Operate
        • Investigate
        • Industrial Control Systems
      • European Skills Framework
    • GIAC Certifications
    • Training Events & Summits
      • Events Overview
      • Event Locations
        • Asia
        • Australia & New Zealand
        • Latin America
        • Mainland Europe
        • Middle East & Africa
        • Scandinavia
        • United Kingdom & Ireland
        • United States & Canada
      • Summits
    • OnDemand
    • Get Started in Cyber
      • Overview
      • Degree and Certificate Programs
      • Scholarships
    • Cyber Ranges
  • Manage Your Team
    Manage Your Team

    Build a world-class cyber team with our workforce development programs

    • Overview
    • Why Work with SANS
    • Group Purchasing
    • Build Your Team
      • Team Development
      • Assessments
      • Private Training
      • Hire Cyber Professionals
      • By Industry
        • Health Care
        • Industrial Control Systems Security
        • Military
    • Leadership Training
  • Security Awareness
    Security Awareness

    Increase your staff’s cyber awareness, help them change their behaviors, and reduce your organizational risk

    • Overview
    • Products & Services
      • Security Awareness Training
        • EndUser Training
        • Phishing Platform
      • Specialized
        • Developer Training
        • ICS Engineer Training
        • NERC CIP Training
        • IT Administrator
      • Risk Assessments
        • Knowledge Assessment
        • Culture Assessment
        • Behavioral Risk Assessment
    • OUCH! Newsletter
    • Career Development
      • Overview
      • Training & Courses
      • Professional Credential
    • Blog
    • Partners
    • Reports & Case Studies
  • Resources
    Resources

    Enhance your skills with access to thousands of free resources, 150+ instructor-developed tools, and the latest cybersecurity news and analysis

    • Overview
    • Webcasts
    • Free Cybersecurity Events
      • Free Events Overview
      • Summits
      • Solutions Forums
      • Community Nights
    • Content
      • Newsletters
        • NewsBites
        • @RISK
        • OUCH! Newsletter
      • Blog
      • Podcasts
      • Summit Presentations
      • Posters & Cheat Sheets
    • Research
      • White Papers
      • Security Policies
    • Tools
    • Focus Areas
      • Cyber Defense
      • Cloud Security
      • Digital Forensics & Incident Response
      • Industrial Control Systems
      • Cyber Security Leadership
      • Offensive Operations
  • Get Involved
    Get Involved

    Help keep the cyber community one step ahead of threats. Join the SANS community or begin your journey of becoming a SANS Certified Instructor today.

    • Overview
    • Join the Community
    • Work Study
    • Teach for SANS
    • CISO Network
    • Partnerships
    • Sponsorship Opportunities
  • About
    About

    Learn more about how SANS empowers and educates current and future cybersecurity practitioners with knowledge and skills

    • SANS
      • Overview
      • Our Founder
      • Awards
    • Instructors
      • Our Instructors
      • Full Instructor List
    • Mission
      • Our Mission
      • Diversity
      • Scholarships
    • Contact
      • Contact Customer Service
      • Contact Sales
      • Press & Media Enquiries
    • Frequent Asked Questions
    • Customer Reviews
    • Press
    • Careers
  • Contact Sales
  • SANS Sites
    • GIAC Security Certifications
    • Internet Storm Center
    • SANS Technology Institute
    • Security Awareness Training
  • Search
  • Log In
  • Join
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. Month of PowerShell - Discoveries from the Month of PowerShell
370x370_Joshua-Wright.jpg
Joshua Wright

Month of PowerShell - Discoveries from the Month of PowerShell

A final wrap-up from the Month of PowerShell: discoveries, recommendations, complaints, and successes.

August 4, 2022

#monthofpowershell

In the month that I spent using PowerShell for every action, I learned a lot more about the platform. Some of the things I learned are great, others are ... not-so-great. In this article I've captured some closing notes about what I've learned in the Month of PowerShell.

The Not-So-Great Things

First let's talk about some of the PowerShell things that fall under the not so great category.

Windows First Features

It's not a huge surprise that PowerShell is most powerful on Windows. WMI, registry access, CIM, .NET API access, etc. PowerShell is most effective on Windows. Other platforms take a back seat.

A lot of the restrictions I ran into with PowerShell were in accessing data using available cmdlets and less about the scripting language or the interface itself. For example, on Windows we can get process information using Get-Process:

PS C:\WINDOWS\system32> Get-Process lsass | Select-Object -Property Id

 Id
 --
632

However, Get-Process does not us to get the parent process ID. For this, you need to use Get-CimInstance:

PS C:\WINDOWS\system32> Get-CimInstance -ClassName Win32_Process | Where-Object -Property Name -EQ "lsass.exe" | Select-
Object -Property ProcessId, ParentProcessId

ProcessId ParentProcessId
--------- ---------------
      632             488

Get-Process is part of the Microsoft.PowerShell.Management module, which is available in Linux and macOS versions of PowerShell as well. However, Get-CimInstance is part of the CimCmdlets module for Common Information Model data access, which is only available on Windows systems.

What do you do if you need the parent process ID on Linux or macOS? You don't use PowerShell.

Maybe this is too harsh, and I shouldn't expect Microsoft to have better support for non-Microsoft platforms. What I would really like is for the Microsoft.PowerShell.Management modules to be more comprehensive in the properties they make available, so I don't have to use Get-CimInstance to get information like the parent process ID or the location of an executable used in a service.

Redirect Flexibility

I made this mistake about 100 times:

~/Dev/allmyhacks> pbcopy < exploit.py
ParserError:
Line |
   1 |  pbcopy < exploit.py
     |         ~
     | The '<' operator is reserved for future use.

This could be a me problem, where I am in the habit of using < to redirect content to STDIN. Microsoft would have us use the pipeline instead:

~/Dev/allmyhacks> Get-Content exploit.py | pbcopy
~/Dev/allmyhacks>

Perhaps this is a habit I should break, but I'm not the only one that uses < this way. Early in the month, I discovered that a lot of my Vim plugins stopped working with curious errors, largely because they expect a POSIX-compliant shell that supports <.

Maybe the lack of < support is a credit to Microsoft: it is often confusing for new Bash users to learn, and it is unnecessary as long as you retrieve the file contents in advance and use the pipeline to send the contents as STDIN. Maybe it's time to let go of the < habit, and plan out the data you wish to access in advance. This is one of many things about PowerShell that seems like an arbitrary feature decision – < isn't used for anything, so why not make it work like other shell environments (including the CMD shell)?

No official word from Microsoft on the future of <, AFAICT.

I Need to Break Out of Text Processing

Throughout the month, I would try to solve problems using the methods that work for me using Bash. For example, I wanted to count how many pages of articles I wrote for the Month of PowerShell. First, I took all of the articles I wrote for the month and converted the Markdown source into PDF. Then I started looking at the PDF metadata to retrieve the page count information. Getting the page count metadata is a job for ExifTool:

~/Desktop/MOPS-Articles> exiftool 'Month of PowerShell - Working with the Registry.pdf'
ExifTool Version Number         : 12.16
File Name                       : Month of PowerShell - Working with the Registry.pdf
Directory                       : .
File Size                       : 414 KiB
File Modification Date/Time     : 2022:07:20 22:01:35-04:00
File Access Date/Time           : 2022:07:20 22:03:01-04:00
File Inode Change Date/Time     : 2022:07:20 22:01:35-04:00
File Permissions                : rw-r--r--
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.4
Linearized                      : No
Page Count                      : 9
Tagged PDF                      : Yes
Creator                         : Chromium
Producer                        : Skia/PDF m104
Create Date                     : 2022:07:21 02:01:34+00:00
Modify Date                     : 2022:07:21 02:01:34+00:00

Using ExifTool, I can get the metadata in the PDF, including the Page Count property. Next I eliminated the other properties using Select-String like I would otherwise use grep on macOS or Linux:

~/Desktop/MOPS-Articles> exiftool 'Month of PowerShell - Working with the Registry.pdf'  | Select-String 'Page Count'

Page Count                      : 9

This gives me the page count, but I want the number by itself to build an array of values that I can easily sum. To strip out the Page Count : information, I used the string -Split feature using : as a delimiter:

~/Desktop/MOPS-Articles> exiftool 'Month of PowerShell - Working with the Registry.pdf'  | Select-String 'Page Count' | foreach { ($_.Line -Split ':')[1] }
 9

By adding the foreach builtin, I can split the output (the Line property from Select-String) on the :, and retrieve the 2nd object (offset value [1]). Next, I expanded this to all of the PDF files, using an array $arr to save each page count value (using the += operator). Once the page counts are all in an array, we can use Measure-Object with the -Sum argument to add them together:

~/Desktop/MOPS-Articles> $arr = @()
~/Desktop/MOPS-Articles> exiftool *pdf | Select-String 'Page Count' | Foreach { $arr += ($_.line -Split ':')[1] }
~/Desktop/MOPS-Articles> $arr | Measure-Object -Sum

Count             : 32
Average           :
Sum               : 165
Maximum           :
Minimum           :
StandardDeviation :
Property          :

I will often tell students in my SEC504: Hacker Tools, Techniques, and Incident Handling class that, when learning a technology, they should focus on getting a task done first, then think about refinement or ways to improve later. Don't let perfection be an obstacle to progress. This approach gets the job done, but it's not the PowerShell way.

Let's redo this task in The PowerShell Way.

Reflecting on this task later, and looking at the documentation for ExifTool, this is a more elegant solution:

~/Desktop/MOPS-Articles> exiftool -json *.pdf -PageCount | ConvertFrom-Json | Select-Object -ExpandProperty PageCount | Measure-Object -Sum

Count             : 32
Average           :
Sum               : 165
Maximum           :
Minimum           :
StandardDeviation :
Property          :

Let's break down this command step-by-step:

  • exiftool -json *.pdf -PageCount |: Use ExifTool similarly, but retrieve the results in JSON format with the argument -json; also limit the output to just the PageCount property; start the pipeline
  • ConvertFrom-Json |: Convert the JSON information returned from ExifTool into a custom PowerShell object using ConvertFrom-JSON; continue the pipeline
  • Select-Object -ExpandProperty PageCount |: Select the page count property, using -ExpandProperty to return an array of just the page count values, continue the pipeline
  • Measure-Object -Sum: Add all of the page count properties using Measure-Object with the -Sum argument

This is a much simpler approach, is less error-prone (what happens if there's a stray : in the previous solution?), and leverages the integral capability for PowerShell to handle data in the pipeline much more gracefully. It does rely on ExifTool's capability to export data in a JSON format (although CSV would work as well using ConvertFrom-CSV). Even without the ability to export in JSON or CSV though, we can use PowerShell's ConvertFrom-StringData to convert the colon-delimited field into a PowerShell object:

~/Desktop/MOPS-Articles> exiftool *.pdf | Select-String 'Page Count' | ConvertFrom-StringData -Delimiter ':' | Select-Object -ExpandProperty 'Page Count' | Measure-Object -Sum

Count             : 32
Average           :
Sum               : 165
Maximum           :
Minimum           :
StandardDeviation :
Property          :

I think the important learning element for me here is this: stop thinking about text output, and start thinking about objects instead. While PowerShell can replace much of the functionality we typically do with Awk, this is less optimal, and it eliminates the opportunity to embrace the pipeline for object access and processing. Where possible, retrieve and convert data in JSON or CSV output using the built-in cmdlets, and if that isn't accessible, convert string data into objects using ConvertFrom-StringData instead.

Stranger Things

One of the most frustrating things about PowerShell is troubleshooting why things don't work when clearly they should 🤬🤯😩.

For example, this works just fine:

PS C:\WINDOWS\system32> $mysession = New-PSSession -ComputerName FM-CEO
PS C:\WINDOWS\system32> Invoke-Command -Session $mysession -ScriptBlock { Get-WinEvent -FilterHashTable @{ LogName = 'System'; Id=7034 } } | Select-Object -Property TimeCreated, PSComputerName, Message

TimeCreated          PSComputerName Message
-----------          -------------- -------
7/20/2022 2:33:06 AM FM-CEO         The Microsoft eDynamics Service service terminated u...
7/20/2022 2:26:50 AM FM-CEO         The Microsoft eDynamics Service service terminated u...
7/20/2022 2:23:03 AM FM-CEO         The Microsoft eDynamics Service service terminated u...

Using New-PSSession and Invoke-Command to run PowerShell commands on remote systems is an amazingly powerful feature. It's also terribly frustrating:

PS C:\WINDOWS\system32> Invoke-Command -Session $mysession -ScriptBlock { Get-WinEvent -FilterHashTable @{ LogName = 'Security'; Id=4624,4634,4672,4732,4648,4688,4768 } }
No events were found that match the specified selection criteria.
    + CategoryInfo          : ObjectNotFound: (:) [Get-WinEvent], Exception
    + FullyQualifiedErrorId : NoMatchingEventsFound,Microsoft.PowerShell.Commands.GetWinEv
   entCommand
    + PSComputerName        : FM-CEO

At first I thought "meh, no events – weird flex but OK" but then I realized there ARE events that match the specified event IDs. It's not good that the error message is misleading to the caller, leading them into thinking the error is just the result of a lack of event IDs.

Why doesn't this work? 🤷‍♂️

The Security event log is only accessible by an administrator, but I'm logging in with administrator access. After a lot of troubleshooting, I was able to make this command work by adding an empty string "" in the beginning of the script block:

PS C:\WINDOWS\system32> Invoke-Command -Session $mysession -ScriptBlock { ""; Get-WinEvent -FilterHashTable @{ LogName =
 'Security'; Id=4624,4634,4672,4732,4648,4688,4768 } }



Message              : An account was logged off.

                       Subject:
                        Security ID:            S-1-5-21-2977773840-2930198165-1551093962-1000
                        Account Name:           Sec504
...

WHY?!?

I ran across some other articles about similar complaints, and presumably this is some fault in PowerShell's handling of a script block where permissions are required to access the Security event log. The deceitful error message returned when using a filter hash table is terrible, particularly when we rely on PowerShell for security event analysis.

Background a Running Process

I will often launch GUI programs from the terminal:

~/Dev/killerbee/sample [develop ≡]> wireshark -r ./control4-sample.pcap

Later, I want to do something else at my terminal while keeping the GUI running. In Bash I would suspend the process using Ctrl+Z, then run bg to background the process. Not so much in PowerShell:

~/Dev/killerbee/sample [develop ≡]> wireshark -r ./control4-sample.pcap
^Zbg

^Z^Z^Z^Z^Z


^Z

🥺

halp?

You can't background a running process in PowerShell. You can Start-Process wireshark and it will run in the background, but you can't suspend and background (you have to close, then launch again).

Other people complain about this deficiency as well. This is probably another issue where new PowerShell users won't have much trouble adapting: if you start a GUI process from the terminal, launch it with Start-Process. Years of being spoiled by Bash has created habits where I expect the flexibility to work and change how processes are running dynamically. It's hard to un-learn those procedures to adapt to PowerShell's limitations.

ForEach Doesn't Output to the Pipeline

PowerShell's foreach has an identity problem.

ForEach: It's a cmdlet! No, no, it's an alias. No, no, it's a ... builtin?

I wrote about this issue in Merging Two Files: Understanding foreach. Depending on how you enter the foreach command, it behaves differently, sometimes outputting to the pipeline, but in other use examples, not.

I don't know why Microsoft overloaded foreach in this way. As a built-in, we could probably just call this for, and reserve ForEach as an alias for ForEach-Object when working with objects in the pipeline. However, it's probably too late to change it now.

Navigating Directories

In Bash, I will use cd - to return to the previous directory. A LOT.

504.22.4 $ pwd
/Users/jwright/Dropbox (SANS)/SEC504/504.22.4
504.22.4 $ cd /Applications/zoom.us.app/Contents/Resources/
Resources $ file leave.pcm
leave.pcm: data
Resources $ cd -
/Users/jwright/Dropbox (SANS)/SEC504/504.22.4
504.22.4 $ # ... continue doing other things

The cd - shortcut is really handy to quickly navigate around the file system, without having to plan out the directory you want to return to in advance.

cd - doesn't exist in PowerShell. 😩

In PowerShell you can use Push-Location and Pop-Location to save and restore your current directory location:

PS C:\WINDOWS\system32\drivers\etc> Push-Location
PS C:\WINDOWS\system32\drivers\etc> cd C:\Tools\nginx\conf\
PS C:\Tools\nginx\conf> select-string "server_name" .\nginx.conf

nginx.conf:37:#        server_name  localhost;
nginx.conf:83:    server_name  wiki;


PS C:\Tools\nginx\conf> Pop-Location
PS C:\WINDOWS\system32\drivers\etc> notepad .\hosts # etc

Here's the big difference:

In Bash, the previous directory is automatic. In PowerShell, you have to plan ahead.

I don't often think ahead when navigating directories, and maybe that's another thing that spoils Bash users. Like the inability to background a running process, PowerShell requires that you plan ahead instead of being flexible enough to adapt to the current work environment.

Good Things

A lot of my frustration with PowerShell came from adapting the things I do in Bash to PowerShell. That's not to say there aren't frustrating things about Bash too, and PowerShell has improved many things over Bash.

Interactive Line Editing

Bash: Oops, I pressed Enter by accident. Start the whole command over again.

PowerShell: Oops, I press Enter by accident (presses backspace to fix).

In PowerShell, the terminal is an interactive editor, complete with keystrokes to navigate up and down across several statements in the same command. If you are typing a string (e.g., there is an open " or ' somewhere) and you press Enter by accident, you can press backspace and continue normally.

This is delightful.

.NET API Access is Amazing

Access to the .NET API makes PowerShell tremendously powerful. A lot of my .NET API use involved calling static methods on classes such as System.IO.Path::GetFileNameWithoutExtension:

~/Desktop/MOPS-Articles> Get-ChildItem *.md | foreach { [System.IO.Path]::GetFileNameWithoutExtension($_.Name) }
Month of PowerShell - 5 Tips for Getting Started with PowerShell
Month of PowerShell - Abusing Get-Clipboard
Month of PowerShell - Cut a Column of Text
Month of PowerShell - Discoveries from the Month of PowerShell
Month of PowerShell - Embracing the Pipeline
...

Some useful .NET classes for everyday PowerShell use include:

  • [System.IO.Path](https://docs.microsoft.com/en-us/dotnet/api/system.io.path)
  • [System.IO.File](https://docs.microsoft.com/en-us/dotnet/api/system.io.file)
  • [System.Math](https://docs.microsoft.com/en-us/dotnet/api/system.math)
  • [System.DateTime](https://docs.microsoft.com/en-us/dotnet/api/system.datetime)
  • [System.Net.Sockets](https://docs.microsoft.com/en-us/dotnet/api/net.sockets.tcpclient) (e.g., the TcpClient class)
  • And much more available in the .NET API Browser

There is a lot of powerful API access and data available in the .NET APIs. I think this is partly why PowerShell is so valuable for attackers, but it's just as powerful for defenders too.

Windows Analysis Can't Be Beat

In addition to all of the .NET API access, PowerShell on Windows can access all of the Common Information Model (CIM) data. We can get a list of the classes available through the Get-CimInstance command using Get-CimClass:

PS C:\Users\Sec504> Get-CimClass -Namespace root/CIMV2 | Where-Object CimClassName -like Win32* | Select-Object CimClass
Name

CimClassName
------------
Win32_DeviceChangeEvent
Win32_SystemConfigurationChangeEvent
Win32_VolumeChangeEvent
Win32_SystemTrace
Win32_ProcessTrace
Win32_ProcessStartTrace
Win32_ProcessStopTrace
Win32_ThreadTrace
...
PS C:\Users\Sec504> (Get-CimClass -Namespace root/CIMV2 | Where-Object CimClassName -like Win32* | Select-Object CimClas
sName).Count
745

To be fair, a lot of the 745 available CIM classes are for performance data: raw and formatted.

Want a list of installed software? Win32_Product is here to help you out:

PS C:\Users\Sec504> Get-CimInstance -Class Win32_Product | Select-Object -Property Name, Version

Name                                                           Version
----                                                           -------
Microsoft Application Compatibility Toolkit 5.6                5.6.7324.0
Microsoft Visual C++ 2019 X86 Minimum Runtime - 14.20.27508    14.20.27508
Microsoft Visual C++ 2010  x86 Redistributable - 10.0.40219    10.0.40219
Microsoft Visual C++ 2013 x86 Minimum Runtime - 12.0.21005     12.0.21005
Microsoft Visual C++ 2013 x86 Additional Runtime - 12.0.21005  12.0.21005
Microsoft Visual C++ 2019 X64 Additional Runtime - 14.24.28127 14.24.28127
Microsoft Visual C++ 2013 x64 Minimum Runtime - 12.0.40649     12.0.40649
Java 8 Update 111                                              8.0.1110.14
Java 8 Update 111 (64-bit)                                     8.0.1110.14
Java SE Development Kit 8 Update 111                           8.0.1110.14
...

Want to check out disk quotas?

PS C:\WINDOWS\system32> Get-CImInstance -Class Win32_DiskQuota

DiskSpaceUsed Limit QuotaVolume                         User
------------- ----- -----------                         ----
0             0     Win32_LogicalDisk (DeviceID = "C:") Win32_Account (Name = "Administrators", Domain = "SEC504STUD...

Want some SID to name mapping information for users and groups?

PS C:\WINDOWS\system32> Get-CImInstance -Class Win32_AccountSid

Element                                                                                Setting
-------                                                                                -------
Win32_SystemAccount (Name = "Everyone", Domain = "SEC504STUDENT")                      Win32_SID (SID = "S-1-1-0")
Win32_SystemAccount (Name = "LOCAL", Domain = "SEC504STUDENT")                         Win32_SID (SID = "S-1-2-0")
Win32_SystemAccount (Name = "CREATOR OWNER", Domain = "SEC504STUDENT")                 Win32_SID (SID = "S-1-3-0")
Win32_SystemAccount (Name = "CREATOR GROUP", Domain = "SEC504STUDENT")                 Win32_SID (SID = "S-1-3-1")
Win32_SystemAccount (Name = "CREATOR OWNER SERVER", Domain = "SEC504STUDENT")          Win32_SID (SID = "S-1-3-2")
...
Win32_Group (Name = "Access Control Assistance Operators", Domain = "SEC504STUDENT")   Win32_SID (SID = "S-1-5-32-579")
Win32_Group (Name = "Administrators", Domain = "SEC504STUDENT")                        Win32_SID (SID = "S-1-5-32-544")
Win32_Group (Name = "Backup Operators", Domain = "SEC504STUDENT")                      Win32_SID (SID = "S-1-5-32-551")
Win32_Group (Name = "Cryptographic Operators", Domain = "SEC504STUDENT")               Win32_SID (SID = "S-1-5-32-569")
Win32_Group (Name = "Distributed COM Users", Domain = "SEC504STUDENT")                 Win32_SID (SID = "S-1-5-32-562")

Not to mention Win32_Process, Win32_Service, Win32_Environment, Win32_Account and many more. There's a lot of power and flexibility in Get-CimInstance waiting to be used.

Data Flexibility

I through I understood PowerShell's flexibility and power for structured data access when I started this project, but after a month I realize it's a lot more powerful than I initially gave it credit for.

Built-in support for reading and writing JSON and CSV files is amazing. I (used to) use JQ a lot for reading JSON data and accessing data properties:

~ $ aws ec2 describe-instances | jq -r '.Reservations[].Instances[].InstanceType'
t2.micro

In PowerShell, we can read a JSON file with Get-Content or use the pipeline and the grouping operator code to access the JSON data as a variable, as shown here:

~> $ec2instances = (aws ec2 describe-instances | ConvertFrom-JSON)
~> $ec2instances

Reservations
------------
{@{Groups=System.Object[]; Instances=System.Object[]; OwnerId=058390151647; ReservationId=r-08679aecdc9c1176c}}

The best part about working with JSON data in PowerShell is tab completion. Type the variable name then your way to access the data:

~> $ec2instances.<TAB>
Reservations  Equals        GetHashCode   GetType       ToString
~> $ec2instances.Reservations.<TAB>
Count           Rank            CompareTo       GetHashCode     GetValue        Set
IsFixedSize     SyncRoot        Contains        GetLength       IndexOf         SetValue
IsReadOnly      Add             CopyTo          GetLongLength   Initialize      ToString
IsSynchronized  Address         Equals          GetLowerBound   Insert          Item
Length          Clear           Get             GetType         Remove          Where
LongLength      Clone           GetEnumerator   GetUpperBound   RemoveAt        ForEach
~> $ec2instances.Reservations.Instances

AmiLaunchIndex                   : 0
ImageId                          : ami-07d02ee1eeb0c996c
InstanceId                       : i-0eabfc3c0b951f348
InstanceType                     : t2.micro
...
~> $ec2instances.Reservations.Instances.InstanceType
t2.micro

Microsoft has done a great job integrated the tools needed to leverage external data sources. This includes JSON data, but also CSV data with ConvertFrom-CSV and any other structured data that we can convert to a PowerShell object using ConvertFrom-StringData.

Conclusion

PowerShell is perfectly acceptable as a shell environment, but tough to transition to if you are used to Bash and Zsh conventions. In many ways, PowerShell excels compared to other shells and scripting languages, but these benefits are primarily limited to Windows. This isn't surprising, but it means that PowerShell still isn't quite ready to replace Bash as my day-to-day shell on macOS and Linux. On Windows systems though, I don't think I'll be as quick to open WSL just to open a Bash shell when I want to script something up or automate a monotonous job.

-Joshua Wright

Start at the beginning: Getting Started With PowerShell


Joshua Wright is the author of SANS SEC504: Hacker Tools, Techniques, and Incident Handling, a faculty fellow for the SANS Institute, and a senior technical director at Counter Hack.

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Recommended Training

  • SEC580: Metasploit for Enterprise Penetration Testing
  • SEC460: Enterprise and Cloud | Threat and Vulnerability Assessment
  • SEC505: Securing Windows and PowerShell Automation

Tags:
  • Cyber Defense
  • Cybersecurity and IT Essentials
  • Penetration Testing and Red Teaming

Related Content

Blog
CD_Blog_HowtoautomateinAzure_Part2_2.jpg
Cyber Defense, Cloud Security
March 2, 2023
How to Automate in Azure Using PowerShell - Part 2
In this post, we will discuss automation approaches to mitigating risks identified in Part 1 of the How to Automate in Azure Using PowerShell series.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
CD_Blog_HowtoautomateinAzure_Part1_2.jpg
Cyber Defense, Cloud Security
October 11, 2022
How to Automate in Azure Using PowerShell - Part 1
In this post, we’ll cover how to automate the assessment and reporting of your cloud security configuration opportunities.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
powershell_option_340x340.jpg
Cybersecurity and IT Essentials, Cyber Defense, Penetration Testing and Red Teaming
July 31, 2022
Month of PowerShell - Keyboard Shortcuts Like a Boss
Let's look at several keyboard shortcuts to speed up your PowerShell sessions.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters & Cheat Sheets
  • White Papers
  • Focus Areas
  • Cyber Defense
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • © 2023 SANS™ Institute
  • Privacy Policy
  • Contact
  • Careers
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn