Перейти к основному содержимому
PowerShell Cmdlets, Objects & Pipeline
Урок 7 из 10

PowerShell Cmdlets, Objects & Pipeline

Work with PowerShell cmdlets and the object pipeline to inspect processes, files and Registry keys accurately, while avoiding common formatting and security misconceptions.

Средний 24 мин Linux и Windows
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Explain why PowerShell passes structured .NET objects across a pipeline instead of plain text
  • Discover cmdlet syntax and object properties using Get-Command, Get-Help and Get-Member
  • Filter, sort and select output from Get-Process and Get-ChildItem in a pipeline
  • Distinguish PowerShell execution policy from real defensive controls such as Script Block Logging

Рекомендуется заранее: Windows Architecture, Processes & Registry BasicsLinux Logs (/var/log) & Bash Essentials

#Why this matters

In Linux administration you pipe text lines between tools such as ps, grep, and awk. That works well when columns stay fixed, yet one unexpected space or changed header breaks a fragile text parser. PowerShell takes a different path: every command passes live .NET objects down the pipeline.

For administrators and security analysts on Windows 10/11 and Server 2019/2022, this design turns routine triage into clean one-liners. Instead of slicing columns by character offset, you ask directly for ProcessName, Path, or LastWriteTime. Notice two editions in the field: Windows PowerShell 5.1 (powershell.exe, built into Windows) and cross-platform PowerShell 7+ (pwsh.exe). The core cmdlets in this lesson work in both.

#Cmdlets and built-in discovery

PowerShell commands are called cmdlets (pronounced "command-lets") and follow a consistent Verb-Noun naming rule, such as Get-Process, Get-ChildItem, Get-Service, or Stop-Process. Verbs describe the action (Get, Set, New, Remove) and singular nouns name the target.

You do not need to memorize hundreds of parameters because three cmdlets help you explore everything locally:

Discovery cmdlet Purpose Example
Get-Command Find commands by name or module Get-Command *Process*
Get-Help Read syntax and usage examples Get-Help Get-ChildItem -Examples
Get-Member Inspect object type, properties and methods Get-Process | Get-Member

Running Get-Process | Get-Member reveals that Get-Process outputs System.Diagnostics.Process objects with properties such as Id, ProcessName, CPU, WorkingSet64, and Path. Even though the console prints a tidy table by default, the underlying object carries dozens of hidden fields.

#Filtering and shaping the object pipeline

The pipe operator | sends each object from one cmdlet to the next. Inside script blocks, the automatic variable $_ (also written $PSItem) represents the current object moving through the pipeline.

  1. Get-ProcessEmit Process objects
  2. Where-ObjectKeep objects matching a condition
  3. Sort-ObjectOrder by a chosen property
  4. Select-ObjectPick specific properties
  5. Export-Csv or ConsoleOutput structured report or table

PowerShell uses dashed comparison operators rather than < or > (because > redirects output to a file):

  • -eq and -ne: equal / not equal (case-insensitive for strings by default)
  • -gt and -lt: greater than / less than
  • -like: wildcard match (*.ps1)
  • -match: regular expression match

Here is a practical triage session combining Get-Process and Get-ChildItem:

powershell
# Find running processes whose binary path sits inside Users, sorted by PID
Get-Process |
  Where-Object { $_.Path -like "C:\Users\*" } |
  Sort-Object Id |
  Select-Object Id, ProcessName, Path

# List files modified in the last 24 hours inside a lab directory
Get-ChildItem -Path C:\Lab -Recurse -File |
  Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) } |
  Select-Object FullName, Length, LastWriteTime
Inspecting a lab folder with Get-ChildItem
$ Get-ChildItem -Path C:\Lab -File | Sort-Object Length -Descending | Select-Object Name, Length

Name               Length
----               ------
capture.pcapng     482190
audit.ps1            1842
notes.txt             312

Notice how Get-ChildItem also works across PSDrives other than the filesystem. Connecting back to the Registry lesson, you can inspect autostart entries natively with Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run".

#Execution policy and real script controls

When you run a .ps1 script file for the first time, Windows PowerShell often blocks it under the default Restricted execution policy. Check your current setting with Get-ExecutionPolicy. Common scopes include Restricted (no scripts), RemoteSigned (local scripts run; downloaded scripts need a signature), and AllSigned (all scripts must be signed).

Real defensive visibility comes from Script Block Logging (recording full executed code blocks under Event ID 4104 in the Microsoft-Windows-PowerShell/Operational log), Module Logging, AMSI (Antimalware Scan Interface, which inspects scripts in memory before execution), and Constrained Language Mode when paired with application allow-listing.

#Defending and common mistakes

  • Using Format-* mid-pipeline: Always filter, sort, and Select-Object first; format only for screen display at the end.
  • Writing = instead of -eq: In PowerShell, = assigns a value rather than comparing it, silently turning a Where-Object filter into a bug.
  • Writing aliases inside saved scripts: Aliases like gci, ps, ?, or % save keystrokes interactively, but full cmdlet names (Get-ChildItem, Where-Object, ForEach-Object) keep team scripts readable and maintainable.
  • Relying on ExecutionPolicy for defence: Enable PowerShell Script Block Logging (Event ID 4104) and ship logs centrally so obfuscated or -EncodedCommand activity is captured.

#Summary

PowerShell cmdlets follow a predictable Verb-Noun structure and pass rich .NET objects down the pipeline rather than raw text. Using Get-Command, Get-Help, and Get-Member, you can discover properties and filter results reliably with Where-Object, Sort-Object, and Select-Object. Keep formatting at the end of the pipeline, and rely on Script Block Logging and AMSI rather than execution policy for security monitoring.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания