Learn PowerShell: Episode 1, The Basics
Table of Contents
Introduction
This tutorial serves as an introduction to PowerShell, guiding you through its basic functionalities and commands. By the end of this guide, you'll understand key concepts and commands that will enable you to effectively use PowerShell for various tasks.
Chapter 1: Getting Started
- Understanding PowerShell: PowerShell is a powerful command line interface built on .NET. It allows users to automate tasks and manage system configurations efficiently.
- Installation:
- Windows comes with an older version of PowerShell (version 5).
- For the latest version, download it from the PowerShell GitHub page.
Chapter 2: Objects
-
Key Concept: PowerShell operates with objects rather than plain text. Each command returns objects that contain properties and methods.
-
Example: When using the command
ls
, PowerShell returns objects representing files and folders with properties like Name, Path, and Extension. -
Viewing Object Properties: Use
Format-List
to display detailed properties of objects.ls | Format-List
Chapter 3: Pipeline
-
Using the Pipeline: You can pass objects from one command to another using the pipe (
|
) operator. -
Example with
Get-Process
: UseGet-Process
to retrieve running processes and display them in a list format.Get-Process | Format-List
-
Measuring Objects: Use
Measure-Object
to calculate statistics like count, average, and sum.ls | Measure-Object
Chapter 4: Filtering with Where
-
Filtering Objects: The
Where
command filters objects based on specified conditions. -
Example: To find all
.txt
files, run:ls | Where { $_.Extension -eq '.txt' }
Chapter 5: Sorting with Sort
-
Sorting Objects: Use the
Sort-Object
command to order objects based on a specific property.ls | Sort-Object -Property Name
Chapter 6: Using ForEach
-
Iterating Over Objects: The
ForEach
command allows you to perform actions on each object in a collection. -
Example: Print a message for each file:
ls | ForEach { echo "I found a file: $_.Name" }
Chapter 7: Putting It All Together
- Practical Application: To calculate the average CPU time of processes with an ID above 4000, follow these steps:
-
Get all processes:
Get-Process
-
Filter processes with ID > 4000:
Get-Process | Where { $_.ID -gt 4000 }
-
Extract CPU time:
Get-Process | Where { $_.ID -gt 4000 } | ForEach { $_.CPU }
-
Calculate average CPU time:
Get-Process | Where { $_.ID -gt 4000 } | ForEach { $_.CPU } | Measure-Object -Average
-
Conclusion
You've learned the basics of PowerShell, including object handling, filtering, sorting, and iterating through collections. These foundational skills will empower you to automate tasks and manage system configurations effectively. In the next tutorial, expect a deeper dive into commands, parameters, and discovering new functionalities within PowerShell. Happy scripting!