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:
-
Get-Process→ gets all processes -
Output goes to
Sort-Object - 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
| Command | Purpose |
|---|---|
Where-Object | Filter data |
Select-Object | Choose properties |
Sort-Object | Sort data |
Measure-Object | Count/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
| Cmdlet | Purpose |
|---|---|
Format-Table | Display in table format |
Format-List | Display as list |
Format-Wide | Show only one property |
Format-Custom | Advanced 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
-AutoSize for clean columns
Format-List for detailed view
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
| Method | Use |
|---|---|
Out-File | Human-readable text |
Export-Csv | Structured data (Excel) |
Set-Content | Simple 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:
-
Get-Service→ produces service objects -
Stop-Service→ accepts those objects directly - 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
| Type | Meaning |
|---|---|
| ByValue | Whole object passed |
| ByPropertyName | Match 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?
-
Get-Service→ returns service objects -
Select Name→ creates objects with propertyName -
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?
-
Get-Processruns first - Returns all processes
-
.Countis 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?
-
Get-Process→ get all processes -
Where-Object→ filter CPU > 100 -
Sort-Object→ highest CPU first -
Select-Object→ pick columns -
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 withOut-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:
- Filter rows
- Sort data
- Select columns
- 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-Objectchanges 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
| Part | Meaning |
|---|---|
@{} | Hashtable |
Name | New column name |
Expression | Logic 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
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not equal |
-gt | Greater than |
-lt | Less than |
-ge | Greater or equal |
-le | Less or equal |
-like | Pattern match |
-match | Regex 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
Post a Comment