Blog navigation

Najnowsze posty

9 wyświetlenia 0 Lubię
Read more
9 wyświetlenia 0 Lubię
Read more
12 wyświetlenia 0 Lubię
Read more
7 wyświetlenia 0 Lubię
Read more
9 wyświetlenia 0 Lubię
Read more

PowerShell — automatyzacja zarządzania Windows Server dla administratorów

98 Odsłony 0 Polubiony
 

PowerShell to zaawansowana powloka wiersza polecen i jezyk skryptowy od Microsoftu, ktory zrewolucjonizowal sposob zarzadzania infrastruktura IT. Dla administratorow Windows Server to absolutnie niezbedne narzedzie — pozwala automatyzowac powtarzalne zadania, zarzadzac setkami serwerow jednoczesnie i wykonywac w minuty operacje, ktore recznie zajmowalyby godziny.

Czym jest PowerShell i dlaczego kazdy administrator powinien go znac?

PowerShell to znacznie wiecej niz zwykly wiersz polecen. To obiektowy jezyk skryptowy oparty na platformie .NET, ktory pozwala na interakcje z praktycznie kazdym elementem ekosystemu Windows — od systemu plikow, przez rejestr, po Active Directory, Hyper-V i uslugi chmurowe Azure.

  • Obiektowosc — PowerShell operuje na obiektach .NET, nie na tekście.
  • Potoki (pipeline) — wyniki jednego polecenia mozna przekazac do nastepnego.
  • Cmdlety — polecenia Czasownik-Rzeczownik (Get-Process, Set-Service).
  • Zdalny dostep — zarzadzanie wieloma serwerami jednoczesnie.
  • Rozszerzalnosc — moduly dla AD, Exchange, SQL Server, Azure.

PowerShell vs CMD vs Bash

CechaCMDBashPowerShell 7
Typ danychTekstTekstObiekty .NET
WieloplatformowoscTylko WindowsLinux/macOSWindows, Linux, macOS
Zarzadzanie ADOgraniczoneBrakPelne moduly
Zdalne zarzadzaniePsExecSSHWinRM + SSH + PSRemoting
Obsluga bledowKody wyjsciatrapTry/Catch/Finally

Dla administratora Windows Server 2022 czy Windows Server 2025 PowerShell to optymalne narzedzie.

Instalacja PowerShell 7 na Windows Server

winget install --id Microsoft.PowerShell --source winget
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI -Quiet"

Po instalacji: pwsh --version. PS 7 wspolistnieje z PS 5.1.

Podstawowe cmdlety

Procesy i uslugi

Get-Process | Where-Object { $_.WorkingSet64 -gt 100MB } | Sort-Object WorkingSet64 -Descending
Restart-Service -Name "Spooler" -Force
Get-Service -Name "DNS","NTDS","W3SVC" | Format-Table Name, Status, StartType

Pliki

Get-ChildItem -Path "C:\Logs" -Recurse -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } | Remove-Item -Force

System

Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, FreePhysicalMemory
Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID, @{N='FreeGB';E={[math]::Round($_.FreeSpace/1GB,2)}}
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10

Skryptowanie — zmienne, petle, funkcje

$servers = @("DC01", "SQL01", "WEB01", "FILE01")
$freeSpace = (Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'").FreeSpace / 1GB
if ($freeSpace -lt 10) {
    Write-Warning "KRYTYCZNIE: Mniej niz 10 GB!"
} elseif ($freeSpace -lt 50) {
    Write-Warning "Mniej niz 50 GB wolnego."
} else {
    Write-Host "OK: $([math]::Round($freeSpace,2)) GB wolnego." -ForegroundColor Green
}

foreach ($server in $servers) {
    $status = Invoke-Command -ComputerName $server -ScriptBlock { Get-Service "W32Time" | Select-Object Status }
    Write-Host "$server - W32Time: $($status.Status)"
}
function Test-ServerHealth {
    [CmdletBinding()]
    param([Parameter(Mandatory,ValueFromPipeline)][string[]]$ComputerName, [int]$CpuThreshold=80)
    process {
        foreach ($c in $ComputerName) {
            $cpu = (Get-CimInstance -ComputerName $c Win32_Processor | Measure-Object LoadPercentage -Average).Average
            [PSCustomObject]@{ Server=$c; CpuPct=$cpu; Alert=$cpu -gt $CpuThreshold }
        }
    }
}
"DC01","SQL01" | Test-ServerHealth | Format-Table

Zarzadzanie Active Directory

Active Directory to serce kazdej infrastruktury Windows:

Install-WindowsFeature -Name RSAT-AD-PowerShell
Get-ADUser -Filter {LastLogonDate -lt $((Get-Date).AddDays(-90)) -and Enabled -eq $true} -Properties LastLogonDate | Export-Csv "InactiveUsers.csv"
Import-Csv "NewUsers.csv" | ForEach-Object { New-ADUser -Name "$($_.FirstName) $($_.LastName)" -SamAccountName $_.Username -Enabled $true -ChangePasswordAtLogon $true }
Search-ADAccount -LockedOut | ForEach-Object { Unlock-ADAccount -Identity $_.SamAccountName }

Zarzadzanie Hyper-V

Modul Hyper-V pozwala zarzadzac VM z konsoli:

Get-VM | Format-Table Name, State, CPUUsage, MemoryAssigned, Uptime
New-VM -Name "WebServer01" -MemoryStartupBytes 4GB -NewVHDPath "D:\VMs\WebServer01.vhdx" -NewVHDSizeBytes 60GB -Generation 2
Set-VM -Name "WebServer01" -ProcessorCount 4 -DynamicMemory -MemoryMinimumBytes 2GB -MemoryMaximumBytes 8GB
Checkpoint-VM -Name "WebServer01" -SnapshotName "Pre-Update"
Get-VM | Where-Object { $_.State -eq 'Off' } | Start-VM

Zdalne zarzadzanie — PSRemoting

Enable-PSRemoting -Force
Enter-PSSession -ComputerName "DC01" -Credential (Get-Credential)
$results = Invoke-Command -ComputerName @("DC01","SQL01","WEB01") -ScriptBlock {
    [PSCustomObject]@{ Server=$env:COMPUTERNAME; Uptime=((Get-Date)-(gcim Win32_OperatingSystem).LastBootUpTime).Days; FreeGB=[math]::Round((gcim Win32_LogicalDisk -Filter "DeviceID='C:'").FreeSpace/1GB,2) }
}
$results | Format-Table

Harmonogram zadan

$action = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument "-File C:\Scripts\DailyReport.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "06:00AM"
Register-ScheduledTask -TaskName "Daily Report" -Action $action -Trigger $trigger -Principal (New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest)

Bezpieczenstwo — Execution Policy i JEA

Get-ExecutionPolicy -List
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine
# JEA
New-PSRoleCapabilityFile -Path "HelpDesk.psrc" -VisibleCmdlets @('Restart-Service','Get-Service','Unlock-ADAccount')
Start-Transcript -Path "C:\PSTranscripts\session.txt"

Gotowe skrypty

Monitor serwerow

@("DC01","SQL01","WEB01") | ForEach-Object {
    [PSCustomObject]@{ Server=$_; Status=if(Test-Connection $_ -Count 2 -Quiet){"ONLINE"}else{"OFFLINE"} }
} | Format-Table

Czyszczenie dyskow

@("C:\Windows\Temp","C:\inetpub\logs") | ForEach-Object {
    if (Test-Path $_) { Get-ChildItem $_ -Recurse -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } | Remove-Item -Force -EA SilentlyContinue }
}

Czesto zadawane pytania (FAQ)

Co to jest PowerShell?

Zaawansowana powloka i jezyk skryptowy Microsoftu do automatyzacji administracji Windows, Active Directory, Hyper-V, Exchange i Azure.

Jak uruchomic PowerShell jako administrator?

Win+X → Terminal (Admin) w Windows 11, lub PPM na ikone → Uruchom jako administrator.

PowerShell 5.1 vs 7?

PS 5.1 = .NET Framework, tylko Windows. PS 7 = .NET 8, wieloplatformowy. Uruchamiaj pwsh (PS7) vs powershell (PS 5.1).

Czy PowerShell jest bezpieczny?

Tak — Execution Policy, JEA, Constrained Language Mode, Script Block Logging.

Jak sie nauczyc?

Get-Help, Get-Command, Get-Member. Cwicz na VM Hyper-V. Kurs "PowerShell 101" na learn.microsoft.com.

Potrzebujesz licencji Windows Server?

Oryginalne klucze z natychmiastowa dostawa.

Windows Server 2022 Windows Server 2025 Windows Server 2019

Artykul zaktualizowany: marzec 2026 | Autor: Zespol KluczeSoft

 
Czy ten wpis na blogu był dla Ciebie pomocny?

Dodaj komentarz

Kod zabezpieczający
z VAT
🛒 Do koszyka