Перейти к основному содержимому
PowerShell Scripting for Windows Automation
Урок 8 из 10

PowerShell Scripting for Windows Automation

Build reliable PowerShell scripts using the object pipeline, typed functions, and strict error handling to parse exported Windows event logs.

Средний 24 мин Программирование
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.

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

  • Explain how PowerShell passes structured .NET objects through a pipeline instead of plain text
  • Filter, transform, and summarize datasets using Where-Object, Select-Object, and Group-Object
  • Write reusable functions with CmdletBinding, typed parameters, and try/catch error handling
  • Parse exported Windows Security event data safely while avoiding mid-pipeline formatting pitfalls

Рекомендуется заранее: Bash Scripting: Loops, Functions & Text StreamsRegular Expressions for Logs & Indicator Extraction

#Why this matters

In the previous lesson, you saw how Bash pipelines pass flat lines of text between utilities like sed and awk. PowerShell takes a different approach for Windows 10/11 and Windows Server 2019/2022 administration and incident response: every cmdlet sends structured objects down the pipeline.

Instead of counting whitespace columns or writing fragile regular expressions to slice command output, you access named properties such as $_.Id, $_.TimeCreated, or $_.Status. That makes Windows triage scripts shorter, easier to read, and far less likely to break when output formatting changes.

#The object pipeline and core cmdlets

PowerShell commands use a Verb-Noun convention (Get-Service, Where-Object, Export-Csv). When you connect them with |, each object moves from one stage to the next with its properties intact:

  1. LoadImport-Csv or Get-WinEvent
  2. FilterWhere-Object
  3. SelectSelect-Object
  4. GroupGroup-Object
  5. SaveExport-Csv or ConvertTo-Json
Cmdlet Role in the pipeline Example usage
Where-Object Keep objects matching a condition Where-Object { $_.Status -eq 'Stopped' }
Select-Object Pick properties or top N items Select-Object -First 10 Name, Status
ForEach-Object Run a script block per object ForEach-Object { $_.FullName }
Group-Object Count and bucket by a property Group-Object -Property SourceIp -NoElement
Export-Csv Write objects cleanly to CSV Export-Csv -Path report.csv -NoTypeInformation

Inside a script block, $_ (long form $PSItem) refers to the current object on the pipeline. Comparison operators use hyphenated names rather than symbols: -eq (equal), -ne (not equal), -gt (greater than), and -like (wildcard match).

powershell
Get-Service |
  Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' } |
  Select-Object -Property Name, DisplayName, Status |
  Sort-Object -Property Name

#Functions, parameters, and error handling

Production and triage scripts should validate inputs and fail loudly when a file is missing. Adding [CmdletBinding()] turns a plain function into an advanced function that supports standard parameters such as -Verbose and -ErrorAction.

powershell
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Get-FailedLogonSummary {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$CsvPath,

        [int]$MinimumFailures = 3
    )

    if (-not (Test-Path -LiteralPath $CsvPath)) {
        throw "Log export not found: $CsvPath"
    }

    try {
        Import-Csv -LiteralPath $CsvPath |
            Where-Object { $_.EventId -eq '4625' } |
            Group-Object -Property SourceIp -NoElement |
            Where-Object { $_.Count -ge $MinimumFailures } |
            Sort-Object -Property Count -Descending |
            Select-Object @{Name = 'SourceIp'; Expression = { $_.Name }}, Count
    }
    catch {
        Write-Error "Failed to parse ${CsvPath}: $_"
    }
}

Using -LiteralPath instead of -Path prevents square brackets in filenames from being interpreted as wildcard characters. For scripts that modify files or registry settings, add [CmdletBinding(SupportsShouldProcess)] so you can preview actions safely with -WhatIf.

#Parsing exported Windows event logs

During security investigations, analysts rarely run heavy queries directly against a live domain controller; instead, they inspect an exported .evtx archive or CSV snapshot on a workstation. Three Windows Security Event IDs appear constantly in triage:

  • 4624: Successful account logon.
  • 4625: Failed account logon (useful for spotting brute-force or password-spraying attempts).
  • 4688: A new process was created (shows command-line activity when command-line auditing is enabled).

When querying an offline .evtx file with Get-WinEvent, pass -FilterHashtable so the Windows event engine filters records before building PowerShell objects:

powershell
$events = Get-WinEvent -FilterHashtable @{
    Path = '.\sec-export.evtx'
    Id   = 4625
}
$events |
    Select-Object TimeCreated, Id, @{Name = 'Account'; Expression = { $_.Properties[5].Value }} |
    Select-Object -First 5

#Common mistakes and defensive practices

  • Putting Format-Table in the middle of a pipeline: Format-* cmdlets convert structured objects into display formatting objects. Calling Format-Table before Export-Csv or Where-Object corrupts the output; keep Format-* only as the final display step, if used at all.
  • Using Where-Object after loading huge .evtx files: Filtering millions of events after Get-WinEvent reads them wastes memory and time. Use -FilterHashtable so filtering happens inside the event engine.
  • Swallowing errors silently: Setting $ErrorActionPreference = 'SilentlyContinue' globally hides broken paths and permission errors. Keep errors visible with 'Stop' and explicit try/catch blocks.
  • Keeping interactive aliases in saved scripts: Short aliases like ?, %, or gci save keystrokes at the prompt, but full cmdlet names (Where-Object, ForEach-Object, Get-ChildItem) make shared security scripts readable and auditable.

#Summary

  • PowerShell pipelines pass structured .NET objects with named properties, removing the need to split plain-text columns.
  • Where-Object, Select-Object, Group-Object, and Export-Csv cover most filtering, aggregation, and reporting tasks cleanly.
  • Combining Set-StrictMode -Version Latest, $ErrorActionPreference = 'Stop', [CmdletBinding()], and try/catch makes automation functions safe and predictable.
  • When triaging exported Windows logs, filter early with -FilterHashtable and avoid Format-* cmdlets before exporting or further processing.

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

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

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