Lesson -4 : Using Powershell Pipeline

19. Introduction to the Pipeline

What is a Pipeline?

πŸ‘‰ A pipeline passes the output of one command as input to another command

Command1 | Command2

Simple Meaning

πŸ‘‰
Pipeline = “Take result from one command and send it to the next command”

 

Basic Example

 >>> Get-Process | Sort-Object CPU

 What happens:

  1. Get-Process → gets all processes
  2. Output goes to Sort-Object
  3. Processes sorted by CPU

Another Example

 >>> Get-Service | Where-Object {$_.Status -eq "Running"}

 Select Specific Data

>>> Get-Process | Select-Object Name, Id

PS C:\Windows\System32> Get-Process | Get-Member

   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
Name                       AliasProperty  Name = ProcessName
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize64
PM                         AliasProperty  PM = PagedMemorySize64
SI                         AliasProperty  SI = SessionId
VM                         AliasProperty  VM = VirtualMemorySize64
WS                         AliasProperty  WS = WorkingSet64
Parent                     CodeProperty   System.Object Parent{get=GetParentProcess;}
Disposed                   Event          System.EventHandler Disposed(System.Object, System.EventArgs)
ErrorDataReceived          Event          System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(System.Object, System.Diagn…
Exited                     Event          System.EventHandler Exited(System.Object, System.EventArgs)
OutputDataReceived         Event          System.Diagnostics.DataReceivedEventHandler OutputDataReceived(System.Object, System.Diag…
BeginErrorReadLine         Method         void BeginErrorReadLine()
BeginOutputReadLine        Method         void BeginOutputReadLine()



Then you may use 

>>> Get-Process | Select-Object Name, Id, WorkingSet, SessionId

How Pipeline Works Internally

πŸ‘‰ PowerShell passes objects, not plain text

So each command receives structured data

Multiple Pipeline Stages

>>> Get-Process | Where-Object {$_.CPU -gt 100} | Sort-Object CPU

$_ 

πŸ‘‰ Represents each process (current item) being processed


$_ .CPU

πŸ‘‰ Accesses the CPU property of that process

-gt 100

πŸ‘‰ Means greater than 100

 

{$_.CPU -gt 100} =
“For each process, check if its CPU usage is greater than 100” 

Important Commands in Pipeline

CommandPurpose
Where-ObjectFilter data
Select-ObjectChoose properties
Sort-ObjectSort data
Measure-ObjectCount/summarize

Pro Tip (Very Important)

Most used pattern:

 >>> Get-Command | Where-Object {} | Select-Object {}

 

What does Get-Command do?

It shows:

  • Cmdlets
  • Functions
  • Scripts
  • Aliases

πŸ‘‰ Basically, everything you can run in PowerShell

 

Cmdlets : cmdlets (pronounced command-lets) are built-in commands used to perform specific tasks.

Function: In PowerShell, a function is a custom block of code that you write once and reuse multiple times.

Alias : In PowerShell, an alias is a short name (nickname) for a command.

 

Alias          Actual Command
ls         Get-ChildItem
dir        Get-ChildItem
cd         Set-Location
cat        Get-Content

View All Aliases : Get-Alias

Find Alias for a Command : >>> Get-Alias -Definition Get-ChildItem

Find Command from Alias : >>> Get-Alias ls

Create Your Own Alias : >>> Set-Alias -Name gs -Value Get-Service

Remove Alias >>> Remove-Item Alias:gs



20. Understanding Get Member

Understanding Get-Member in PowerShell

In PowerShell,
Get-Member is used to:

πŸ‘‰ Inspect an object and see what it contains

What does Get-Member show?

It displays:

  • Properties → Data (Name, Id, Status)
  • Methods → Actions (Start(), Stop(), Kill())
  • Type of object


Basic Syntax

<command> | Get-Member

>>> Get-Process | Get-Member

Output shows:

  • Properties: Name, Id, CPU
  • Methods: Kill(), Start()

Why is it important?

πŸ‘‰ Helps you:

  • Understand what data is available
  • Discover properties for filtering
  • Learn how to manipulate objects

Example 2 (Services)

>>> Get-Service | Get-Member

Shows:

  • Status
  • Name
  • Start() method

Using Specific Member Types

Only properties

>>> Get-Process | Get-Member -MemberType Property

Only methods

>>> Get-Process | Get-Member -MemberType Method

Practical Use

>>> Get-Process | Where-Object {$_.CPU -gt 100}


Real-Life Analogy

πŸ‘‰ Get-Member = “Open and inspect what’s inside an object”

Like checking:

  • Features of a phone
  • Functions of a machine

Related Commands

  • Select properties:

>>> Get-Process | Select-Object Name, CPU

Help:

>>> Get-Help Get-Process

21 . Formatting Pipeline Output

In PowerShell, formatting pipeline output means:

πŸ‘‰ Controlling how results are displayed (table, list, wide, etc.)


Why Formatting is Important

  • Makes output easy to read πŸ‘€
  • Shows only required data 🎯
  • Helps in reports πŸ“Š


Main Formatting Cmdlets

CmdletPurpose
Format-TableDisplay in table format
Format-ListDisplay as list
Format-WideShow only one property
Format-CustomAdvanced formatting


Format-Table (Most Used)

>>> Get-Process | Format-Table Name, CPU -AutoSize 

Format-List

>>> Get-Process | Format-List Name, Id

Format-Wide

>>> Get-Process | Format-Wide Name

πŸ‘‰ Shows only names in multiple columns

Format-Custom (Advanced)

>>> Get-Process | Format-Custom
πŸ‘‰ Shows detailed structured output


Real Example

>>> Get-Service | Where-Object {$_.Status -eq "Running"} | Format-Table Name, Status


  • Use -AutoSize for clean columns
  • Use Format-List for detailed view
  • Always format at the end


  • Format into a Text File (Most Common)

    >>> Get-Process | Select Name, CPU | Format-Table -AutoSize | Out-File "C:\process.txt"

    Saves formatted table into a .txt file

    Format as List into File

    >>> Get-Service | Format-List Name, Status | Out-File "C:\services.txt"

    Export as CSV (Best for Excel)

    >>> Get-Process | Select Name, CPU | Export-Csv "C:\process.csv" -NoTypeInformation

    -NoTypeInformation removes the type metadata line from the CSV file.

    πŸ‘‰ Opens in Excel cleanly

    Save Raw Output (No Formatting)

    >>> Get-Process | Select Name, CPU | Out-File "C:\raw.txt"

    Difference Between Methods

    MethodUse
    Out-FileHuman-readable text
    Export-CsvStructured data (Excel)
    Set-ContentSimple text writing


    Important Rule -- Not to do***

    πŸ‘‰ Formatting before exporting can cause issues in CSV

    ❌ Wrong:

    Get-Process | Format-Table | Export-Csv file.csv



    22. Passing Pipeline Data ByValue

     What does Test-NetConnection do?

    πŸ‘‰ It checks:

    • If a server/website is reachable
    • Port connectivity (very important)
    • DNS resolution
    • Network route (like traceroute)

     

    Test-NetConnection <ComputerName>

    Test-NetConnection google.com 

    Test-NetConnection google.com -Port 80

    Test-NetConnection google.com -Port 443

    Test-NetConnection server -Port 3389 -Quiet

    Test-NetConnection google.com -TraceRoute

     

    Read a file in powershell

    >>> Get-Content <file_name> 

    lets say we open up a notepad , add server names line by line and  

    >>> Get-Content <file_name> | Net-TestConnection  

    this will ping all the servers in the file and return the result

    Passing Pipeline Data ByValue in PowerShell

    In PowerShell,
    Passing pipeline data ByValue means:

    πŸ‘‰ The entire object from one command is passed directly to a parameter of the next command

    Simple Definition

    πŸ‘‰ ByValue = pass the whole object automatically (no manual mapping needed)

    Basic Example

     >>> Get-Service | Stop-Service

    What happens:

    1. Get-Service → produces service objects
    2. Stop-Service → accepts those objects directly
    3. Services are stopped

    Why does this work?

    Because:

    πŸ‘‰ Stop-Service accepts input ByValue

      How to Check (Important)

    >>> Get-Help Stop-Service -Full


    πŸ‘‰ Look for:

    Accept pipeline input?  True (ByValue)

    Another Example

    >>>Get-Process | Stop-Process
    πŸ‘‰ Each process object is passed directly

    How ByValue Works Internally

    πŸ‘‰ PowerShell checks:

    • Does the next cmdlet accept this object type?
    • If YES → passes automatically


    Pipeline Flow (ByValue)

    [Process Object] → Stop-Process

     πŸ‘‰ Entire object goes into the command


    Important Note

    ByValue works only when:

    ✔️ Object type matches expected parameter
    ❌ Otherwise it won’t work

     

     ByValue vs ByPropertyName

    TypeMeaning
    ByValueWhole object passed
    ByPropertyNameMatch property names

     Method 1 (Best - ByValue)

    >>> Get-Service | Stop-Service

    Method 2 (Filter + Stop)

    >>> Get-Service | Where-Object {$_.Name -eq "Spooler"} | Stop-Service 

    Method 3 (Explicit parameter)

    >>> Get-Service | Select Name | ForEach-Object {
        Stop-Service -Name $_.Name


    23. Passing Pipeline Data ByPropertyName in PowerShell

    In PowerShell,
    ByPropertyName means:

    πŸ‘‰ Values are passed from one command to another based on matching property names

    Simple Definition

    πŸ‘‰ ByPropertyName = match property names to parameter names


    Basic Example

    >>> Get-Service | Select Name | Stop-Service

    What happens here?

    1. Get-Service → returns service objects
    2. Select Name → creates objects with property Name
    3. Stop-Service → has parameter -Name

    PowerShell matches:

    Name (property) → -Name (parameter)

    Why this works

    πŸ‘‰ Because Stop-Service accepts pipeline input:

    ByPropertyName = True

    Another Example

    >>> Get-Process | Select Id | Stop-Process

    Matches:

    Id → -Id

    Check if command supports it

    >>> Get-Help Stop-Service -Full


    4. Using Parentheses to Change the Order of Operations (PowerShell)

    In PowerShell, parentheses () are used to:

    πŸ‘‰ Force a command or expression to run first (before the rest of the pipeline or expression)

    Simple Definition

    πŸ‘‰ () = “Do this part first”

    Basic Example

    >>> (Get-Process).Count

    What happens?

    1. Get-Process runs first
    2. Returns all processes
    3. .Count is applied

    πŸ‘‰ Output: total number of processes

     

    ❌ Without Parentheses

    Get-Process.Count

    πŸ‘‰ ❌ Error or unexpected result
    πŸ‘‰ Because .Count is not applied correctly

     

    Real Use Case

    Without parentheses

     >>> Get-Process | Select Name, CPU | Measure-Object

    Works, but not flexible for further operations

    With parentheses

     >>> (Get-Process | Select Name, CPU).Count

     or 

    >>> (Get-Process | Select Name, CPU) | Measure-Object 

    or

    >>> (Get-Process) | Select Name, CPU | Measure-Object


    Use in Calculations

     (5 + 3) * 2

    πŸ‘‰ Output: 16
    πŸ‘‰ Without parentheses → 11

     

    Access Object Properties

    >>> (Get-Service -Name Spooler).Status

    πŸ‘‰ Gets status directly

    Why Parentheses Matter

    πŸ‘‰ They:

    • Control execution order
    • Allow property access on results
    • Help in complex pipelines

    Important Notes

    • Always use () when accessing properties of a command
    • Useful in scripting and automation
    • Improves readability

    Real-Life Analogy

    πŸ‘‰ Like math:

    • (2 + 3) × 5 → correct order
    • Without brackets → wrong result

    Simple Explanation

    πŸ‘‰ Parentheses =
    Run this first, then continue

    Pro Tips

    ✔️ Use for counting:

    >>> (Get-Process).Count

    Use for filtering:

    >>> (Get-Service | Where-Object {$_.Status -eq "Running"}).Count

    Use for property access:


    >>> (Get-Date).Day

    >>> Get-Date -Format "dddd, dd MMMM yyyy HH:mm:ss"



    25. Measuring Objects in PowerShell

    In PowerShell, measuring objects means:

    πŸ‘‰ Calculating count, sum, average, min, max of data

    This is done using the cmdlet:

    >>> Measure-Object

    What does Measure-Object do?

    πŸ‘‰ It helps you:

    • Count items
    • Add values
    • Find average
    • Find smallest / largest value


    Basic Syntax

    <command> | Measure-Object

    Example 1: Count Objects

    >>> Get-Process | Measure-Object

    >>> Get-Process | Get-Member -MemberType Property

    >>> Get-Process | Get-Member -MemberType Method

    >>> (Get-Process | Measure-Object -Property CPU).count

    >>> Get-Process | Measure-Object -Property CPU -Sum

    >>> Get-Process | Measure-Object -Property CPU -Average 

     

    Example 5: 
     

    >> Get-Process | Measure-Object -Property CPU -Maximum -Minimum -Average -Sum

     

    >>  Get-ChildItem | Measure-Object -Property Length -Sum

    >>> Get-Process | Where-Object {$_.CPU -gt 100} | Measure-Object

    Interview Tip

    Most common:

    >>> (Get-Process).Count

     

    26. Sorting Objects in PowerShell

    In PowerShell, sorting objects means:

    πŸ‘‰ Arranging data in a specific order (ascending or descending)

    This is done using the cmdlet:

     Sort-Object

     
    What does Sort-Object do?

    πŸ‘‰ It sorts data based on:

    • Numbers
    • Text
    • Dates

     Basic Syntax

     <command> | Sort-Object <Property>

     Example 1: Sort Processes by CPU

    >>> Get-Process | Sort-Object CPU --default is ascending

    Descending Order

    >>> Get-Process | Sort-Object CPU -Descending

     πŸ‘‰ Highest CPU first

    Example 2: Sort by Name

    >>> Get-Service | Sort-Object Name

    Example 3: Sort Files by Size

    >>> Get-ChildItem | Sort-Object Length -Descending

    πŸ‘‰ Largest files first

    Sort Multiple Properties

    >>> Get-Process | Sort-Object CPU, Name

    πŸ‘‰ First by CPU, then by Name

    Select + Sort

    >>> Get-Process | Select Name, CPU | Sort-Object CPU -Descending

    How it Works

    πŸ‘‰ PowerShell looks at the property value
    πŸ‘‰ Rearranges objects accordingly

    Real Example (Top 5 CPU Processes)

    >>> Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

    >>> Get-Process | Sort-Object CPU -Descending | Select-Object -Last 6

    Important Notes

    • Default = Ascending order
    • Works only with valid properties
    • Case-insensitive sorting for text

    Combine with Filtering

    • Get-Process |
    • Where-Object {$_.CPU -gt 100} |
    • Sort-Object CPU -Descending

    Interview Tip

    Most common:

    >>> Get-Process | Sort-Object CPU -Descending | Select -First 10

    πŸ‘‰ Shows top 10 CPU-consuming processes

    Combine Filtering + Sorting + Exporting in PowerShell

    In PowerShell, you can chain multiple steps in one pipeline to:

    >>> Command | Where-Object {} | Sort-Object {} | Export-Csv / Out-File 

    Example 1: High CPU Processes → Sort → Export

    >>>

    Get-Process |
    Where-Object {$_.CPU -gt 100} |
    Sort-Object CPU -Descending |
    Select-Object Name, CPU |
    Export-Csv "C:\HighCPUProcesses.csv" -NoTypeInformation

    What happens?

    1. Get-Process → get all processes
    2. Where-Object → filter CPU > 100
    3. Sort-Object → highest CPU first
    4. Select-Object → pick columns
    5. Export-Csv → save to file

    Example 2: Large Files Report

    Get-ChildItem "C:\Logs" |
    Where-Object {$_.Length -gt 10MB} |
    Sort-Object Length -Descending |
    Select Name, Length |
    Export-Csv "C:\LargeFiles.csv" -NoTypeInformation 

    EXAMPLE

    >>> Get-ChildItem "C:\Users\v-sreejithba" | Where-Object {$_.length -gt "1KB"} | Sort-Object Length -Descending | Select Name, Length

    Name                 Length
    ----                 ------
    process.csv            7363
    HighCPUProcesses.csv   1212

    Example 3: Running Services → Export to Text


    Important Rules

    ✅ Rule 1: Order matters

    πŸ‘‰ Always follow:

    Filter → Sort → Select → Export

    ❌ Rule 2: Don’t format before CSV

    Wrong:

    Format-Table | Export-Csv

    Correct:

    Select-Object | Export-Csv

     

    Rule 3: Use Format-* only for text output

    • Format-Table → use with Out-File
    • NOT with Export-Csv

     

    Example 4: Top 5 Processes Report

    >>> Get-Process |
    Sort-Object CPU -Descending |
    Select-Object -First 5 Name, CPU |
    Export-Csv "C:\TopProcesses.csv" -NoTypeInformation

    Real-Life Analogy

    πŸ‘‰ Like Excel workflow:

    1. Filter rows
    2. Sort data
    3. Select columns
    4. Save file

    Simple Explanation

    πŸ‘‰ Combine like this:

    Get-Data | Filter | Sort | Select | Export

     

    Pro Tips

    ✔️ Use -Descending for top results
    ✔️ Use -First for top N records
    ✔️ Always clean output with Select-Object

     

     

    27. Selecting Objects in PowerShell

    In PowerShell, selecting objects means:

    πŸ‘‰ Choosing specific properties or items from the output

    This is done using:

     Select-Object

     What does Select-Object do?

    πŸ‘‰ It helps you:

    • Pick specific properties (columns)
    • Limit number of results
    • Create custom output

     Basic Syntax

     <command> | Select-Object <Property1>, <Property2>

    Example 1: Select Properties 

    >>> Get-Process | Select-Object Name, CPU

    πŸ‘‰ Output shows only:

    • Name
    • CPU

    Example 2: First Few Objects

    >>> Get-Process | Select-Object -First 5

    πŸ‘‰ Shows first 5 processes

    Example 3: Last Few Objects

    >>> Get-Process | Select-Object -Last 5

    Example 4: Unique Values

    >>> Get-Service | Select-Object Name -Unique

     Lists all services but shows only unique service names (no duplicates)

    Example 5: Expand Property

    >>> Get-Process | Select-Object -ExpandProperty Name

     πŸ‘‰ Outputs only the process names as plain text (not objects) . Returns only values (not objects)

    Example 6: Calculated Property

    >>> Get-Process | Select-Object Name, @{Name="CPU_Usage"; Expression={$_.CPU}}

    Displays process name and CPU usage, but renames the CPU column to CPU_Usage

    Combine with Sorting

    >>> Get-Process |  Sort-Object CPU -Descending | Select-Object -First 5 Name, CPU

    πŸ‘‰ Top 5 CPU processes

    Important Notes

    • Select-Object changes the object structure
    • Use carefully before actions like Stop-Process
    • Best used for:
      • Display
      • Export

    Real-Life Analogy

    πŸ‘‰ Like choosing columns in Excel:

    • Hide unwanted columns
    • Show only needed data

    Interview Tip

    Most used:

    >>> Get-Process | Select Name, Id, CPU



    28. Creating Calculated Properties Using Select-Object

    In PowerShell,
    calculated properties let you:

    πŸ‘‰ Create new columns (custom fields) based on existing data

    πŸ”‘ Simple Definition

    πŸ‘‰ Calculated Property =
    A new property created using an expression

    Basic Syntax

    Select-Object Property1, @{Name="NewColumn"; Expression={ <logic> }}


    Example 1: Rename Property

    >>> Get-Process | Select-Object Name, @{Name="CPU_Usage"; Expression={$_.CPU}}

    Output:

    Name      CPU_Usage
    ----      ----------
    chrome    120
    notepad   5 

    Example 2: Convert Units (Bytes → MB)

    >>> Get-ChildItem | Select-Object Name,
    @{Name="SizeMB"; Expression={ $_.Length / 1MB }}


    Example 3: Round Values

    >>> Get-ChildItem | Select-Object Name,
    @{Name="SizeMB"; Expression={ [math]::Round($_.Length / 1MB, 2) }}

    Example 4: Custom Date Format

    >>> Get-Process | Select Name,
    @{Name="StartDate"; Expression={ $_.StartTime.ToString("yyyy-MM-dd") }}


    Example 5: Conditional Logic

    >>> Get-Process | Select Name,
    @{Name="HighCPU"; Expression={ if ($_.CPU -gt 100) {"Yes"} else {"No"} }}

    Example 6: Multiple Calculated Properties

    >>> Get-Process | Select Name,
    @{Name="CPU"; Expression={$_.CPU}},
    @{Name="MemoryMB"; Expression={ $_.WorkingSet / 1MB }}

    How it Works

    PartMeaning
    @{}Hashtable
    NameNew column name
    ExpressionLogic to calculate value


    Combine with Export

    Get-Process |
    Select Name,
    @{Name="CPU"; Expression={$_.CPU}},
    @{Name="MemoryMB"; Expression={ $_.WorkingSet / 1MB }} |
    Export-Csv "C:\ProcessReport.csv" -NoTypeInformation



    29. Filtering Objects in PowerShell

    In PowerShell,
    filtering objects means:

    πŸ‘‰ Selecting only the data that meets specific conditions

    Main Cmdlet

    >>  Where-Object


    Basic Syntax

    <command> | Where-Object { condition }

    Key Concept

    πŸ‘‰ Inside {}:

    • $_ = current object
    • You apply a condition


    Example 1: Filter Running Services

    >>> Get-Service | Where-Object {$_.Status -eq "Running"}

    πŸ‘‰ Shows only running services

    Example 2: Filter High CPU Processes

    >>> Get-Process | Where-Object {$_.CPU -gt 100}

    πŸ‘‰ Shows processes using more CPU

    Example 3: Filter Files by Size

    >>> Get-ChildItem | Where-Object {$_.Length -gt 10MB}

    πŸ‘‰ Files larger than 10 MB

    Comparison Operators

    OperatorMeaning
    -eqEqual
    -neNot equal
    -gtGreater than
    -ltLess than
    -geGreater or equal
    -leLess or equal
    -likePattern match
    -matchRegex match

    Example 4: Filter by Name

    >>> Get-Process | Where-Object {$_.Name -like "*chrome*"}

    Example 5: Case-insensitive match 

    >>> Get-Service | Where-Object {$_.Name -match "win"}


    Multiple Conditions

    >>> Get-Process |
    Where-Object { $_.CPU -gt 100 -and $_.Name -like "*chrome*" }

    Combine with Sorting

    >>> Get-Process |
    Where-Object {$_.CPU -gt 50} |
    Sort-Object CPU -Descending

    Important Notes

    • Filtering happens after data is retrieved
    • Works on object properties
    • Can impact performance for large data




    Comments