🔷 PowerShell
Командлеты, конвейер объектов, переменные, условия, циклы, функции и работа с файлами и сервисами.
Шпаргалки · Администрирование · #powershell #windows #shell #scripting
Основное
PowerShell работает с объектами, а не с текстом. Команды называются командлетами: Глагол-Существительное.
Get-Help Get-Process -Examples # справка
Get-Command *service* # найти команды
Get-Member # свойства и методы объекта
$PSVersionTable # версия
Запуск скриптов: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser.
Конвейер
Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | Select-Object -First 5 Name, CPU
Get-ChildItem -Recurse *.log | Measure-Object Length -Sum
Get-Service | Where-Object Status -eq 'Running' | Export-Csv services.csv -NoTypeInformation
Сокращения: ? = Where-Object, % = ForEach-Object, ls, cat, cd, gci.
Переменные и типы
$name = "Аня"; [int]$n = 5; $arr = 1, 2, 3
$h = @{ a = 1; b = 2 }; $h.a
"Привет, $name"; "Сумма: $($n + 1)"
$env:PATH; $PWD; $HOME
Условия и циклы
if ($n -gt 5) { "много" } elseif ($n -eq 5) { "пять" } else { "мало" }
foreach ($f in Get-ChildItem *.txt) { $f.Name }
1..5 | ForEach-Object { $_ * 2 }
while ($i -lt 3) { $i++ }
switch ($x) { 1 { "один" } default { "другое" } }
Операторы: -eq -ne -gt -lt -ge -le -like -match -contains -in -and -or -not.
Функции
function Get-Square {
param([Parameter(Mandatory)][int]$Number)
$Number * $Number
}
Get-Square -Number 4
Файлы
Get-Content log.txt -Tail 50 -Wait
"текст" | Out-File a.txt -Encoding utf8
Set-Content b.txt "строка"; Add-Content b.txt "ещё"
Copy-Item a.txt D:\backup\; Move-Item; Remove-Item -Recurse -Force old
Test-Path C:\temp; New-Item -ItemType Directory logs
Select-String -Path *.log -Pattern "ERROR"
Система и сеть
Get-Service; Restart-Service nginx; Get-EventLog -LogName System -Newest 20
Stop-Process -Name notepad; Get-NetTCPConnection -State Listen
Test-NetConnection example.com -Port 443
Invoke-RestMethod https://api.example.com/v1 -Headers @{Authorization = "Bearer $t"}
Invoke-WebRequest https://example.com/f.zip -OutFile f.zip
Ошибки
try { Get-Item nofile -ErrorAction Stop } catch { Write-Host "Ошибка: $($_.Exception.Message)" } finally { }
$ErrorActionPreference = 'Stop'
Удалённо
Enter-PSSession -ComputerName srv, Invoke-Command -ComputerName srv -ScriptBlock { Get-Service }, SSH-подключение в PowerShell 7.