PowerShell: відмінності між версіями
R (обговорення | внесок) Створена сторінка: {{SEO|title=PowerShell — shell, scripting language, automation, objects pipeline, modules, remoting, DevOps і адміністрування Windows/Linux/macOS|description=PowerShell — Wiki-стаття про кросплатформений shell і scripting language від Microsoft для автоматизації, адміністрування, DevOps, CI/CD, Azure, Microsoft 365, Windows Server, Linux/macOS, objects pipeline, cmdlets, module... |
R (обговорення | внесок) Немає опису редагування |
||
| Рядок 1: | Рядок 1: | ||
</pre> | |||
DSC має окрему історію версій і сценаріїв, з цієї причини для production потрібно перевіряти актуальну документацію під конкретну платформу.;== $ErrorActionPreference == | |||
== Пояснення термінів == | |||
PowerShell має cmdlets для файлів: | |||
</pre> | </pre> | ||
| Рядок 5: | Рядок 10: | ||
<pre> | <pre> | ||
Get- | Get-Content | ||
* enterprise; | |||
* production scripts; | |||
* security policies; | |||
* regulated environments; | |||
* deployment automation.; Сценарії: | |||
</pre> | |||
PowerShell відрізняється від багатьох shell тим, що передає між командами не без ускладнень текст, а '''об’єкти'''.;== Коли PowerShell має змогу бути невдалим вибором == | |||
[CmdletBinding()] | |||
== PowerShell у DevOps == | |||
PowerShell має сильну систему parameters.; Додавання: | |||
$data = Import-Csv .\users.csv | |||
<pre> | |||
Він не веде обліковий облік, не проводить документи й не керує складом сам по собі.;</pre> | |||
== PowerShell і формування звітів == | |||
Pester корисний для: | |||
<pre> | |||
= | <pre> | ||
Функція: | |||
<pre> | |||
PowerShell має single-quoted і double-quoted strings.; [xml]$xml = Get-Content .\config.xml | |||
Get-ChildItem | |||
<pre> | |||
</pre> | </pre> | ||
Get- | $items [0] | ||
'''Azure PowerShell''' — модулі для керування Azure.; У GitHub Actions можна використовувати PowerShell.; # Обробляти помилки через <code>try/catch</code>.; Інструмент !!;<pre> | |||
<pre> | |||
Get-Service | |||
<code>$_</code> означає поточний об’єкт pipeline.; * '''PSScriptAnalyzer''' — статичний аналізатор PowerShell-коду.; Але PowerShell не повинен обходити бізнес-логіку ERP, права доступу або audit.; * <code>Write-Warning</code> — warning.;<ref>https://github.com/PowerShell/PowerShell</ref> | |||
[[Категорія:Адміністрування]] | |||
Це надає можливість: | |||
) | |||
У корпоративному середовищі PowerShell повинен бути видимим для security teams.;</pre> | |||
[string]$Name | |||
* deployment scripts; | |||
* backup scripts; | |||
</pre> | * automation around Windows services; | ||
* log collection; | |||
* scheduled exports; | |||
* API calls; | |||
* monitoring checks; | |||
* CI/CD; | |||
* адміністративних задач; | |||
* integration scripts; | |||
* генерації технічних звітів.; Remove-Item .\old-files\* -WhatIf | |||
PowerShell краще для адміністрування Windows/Microsoft 365/Azure.;<code>Invoke-Command</code> виконує script block локально або віддалено.; PowerShell дуже зручний для CSV.; * '''SecretManagement''' — підхід і модулі для роботи з secrets.; * style issues; | |||
* potential bugs; | |||
* security problems; | |||
* deprecated patterns; | |||
* best practice violations.; Краще використовувати collections або pipeline.; * <code>Write-Host</code> — вивід на екран.; Але не всі modules однаково працюють на всіх платформах.; * '''Code signing''' — цифровий підпис scripts.;</pre> | |||
'''Execution Policy''' — механізм, який контролює запуск scripts у Windows PowerShell/PowerShell.; Exit-PSSession | |||
Сильні сторони: | |||
<pre> | |||
<code>Where-Object</code> фільтрує об’єкти.;</pre> | |||
$config = @{ | |||
Invoke-RestMethod | |||
Імпорт: | |||
Приклад: | |||
PowerShell має error handling через <code>try/catch/finally</code>.; * '''DSC''' — Desired State Configuration.; Він сприяє знаходити: | |||
</pre> | </pre> | ||
</pre> | |||
PowerShell часто функціонує з secrets: | |||
Remoting потребує правильної безпеки, автентифікації й мережевих налаштувань.; # Не зберігати secrets у scripts.;== Практичний висновок == | |||
$name = " | </pre> | ||
$name = "Anna" | |||
</pre> | </pre> | ||
Find-Module Pester | |||
== Dry run і WhatIf == | |||
[[Категорія:DevOps]] | |||
</pre> | </pre> | ||
* адміністрування серверів; | Це радше safety feature, яка сприяє запобігти випадковому запуску небажаних scripts.; * '''Pipeline''' — передача результатів однієї команди в іншу.; * адміністрування серверів; | ||
* масових змін; | * масових змін; | ||
* audit; | * audit; | ||
| Рядок 92: | Рядок 116: | ||
* troubleshooting; | * troubleshooting; | ||
* Windows Server; | * Windows Server; | ||
* hybrid environments.; | * hybrid environments.; [Parameter(Mandatory)] | ||
</pre> | |||
PowerShell automation має логувати результат.;<code>Get-Help</code> показує довідку.; * '''Splatting''' — передача параметрів через hashtable.; # Дотримуватися least privilege.; -Method Post ` | |||
</pre> | |||
* SecretManagement module; | |||
* SecretStore; | |||
* Azure Key Vault; | |||
* Windows Credential Manager; | |||
* environment variables; | |||
* CI/CD secret storage; | |||
* managed identities.;== PowerShell і ERP-системи == | |||
Сучасний PowerShell запускається командою: | |||
Windows PowerShell зазвичай запускається як: | |||
# commands | |||
Приклад: | |||
У контексті [[K2 ERP]] PowerShell має змогу бути корисним для: | |||
== | Azure Pipelines має PowerShell tasks.;[[Категорія:Microsoft 365]] | ||
Write-Verbose "Done" | |||
Get-ChildItem *.log | ForEach-Object { | |||
active = $true | |||
Вихід: | |||
== Scheduled jobs і Task Scheduler == | |||
Get-AzVM | |||
== Least privilege == | |||
Приклад: | |||
[[Категорія:Програмування]] | |||
AD cmdlets зазвичай доступні через RSAT/ActiveDirectory module.; Це пульт керування системою, де команди повертають структуровані об’єкти, а не “кашу” з тексту.; Для catch часто потрібно <code>-ErrorAction Stop</code>.; 'Hello, $name' | |||
Це | |||
</pre> | |||
</pre> | </pre> | ||
Це краще, ніж просити користувача вводити password у plain text.; $body = @{ | |||
''' | |||
* script block logging; | |||
* module logging; | |||
* transcription; | |||
* constrained language mode; | |||
* AMSI; | |||
* event logs; | |||
* Defender integration; | |||
* SIEM forwarding.; * '''Job''' — фонова задача PowerShell.; Команди: | |||
У корпоративному середовищі встановлення модулів має змогу бути обмежене політиками.;<pre> | |||
== Write-Output, Write-Host, Write-Error == | |||
== Get-Command == | |||
PowerShell | [[Категорія:Shell]] | ||
Якщо написано <code>pwsh</code>, це PowerShell 7+.; } | |||
== PowerShell у GitHub Actions == | |||
Приклад: | |||
Під час роботи з PowerShell варто: | |||
== Дивіться додатково == | |||
} | |||
Команди: | |||
$response = Invoke-RestMethod -Uri "https://api.example.com/users" | |||
Hashtables часто використовують для параметрів, конфігурації, JSON-подібних структур і splatting.; Приклад: | |||
У документації краще писати повну форму, бо вона зрозуміліша.; Приклад: | |||
$job = Start-Job -ScriptBlock { | |||
Windows PowerShell часто застосовується для Active Directory.; PowerShell functions можуть поводитися як cmdlets, якщо правильно описати parameters.; param( | |||
.\script.ps1 -Force | |||
"Force mode enabled" | |||
* resource management; | |||
* automation; | |||
* deployment; | |||
* audit; | |||
* reporting; | |||
* governance.; '''Чому це істотно:''' у PowerShell не потрібно парсити колонки тексту.; компонент має змогу містити: | |||
== PowerShell і Windows PowerShell == | |||
* '''Windows PowerShell 5.1''' — стара реліз, вбудована у Windows, функціонує на .NET Framework.; * <code>Write-Error</code> — error stream.; $config.Timeout | |||
Приклад: | |||
Це покаже команди, пов’язані із сервісами.;== Arrays == | |||
Приклад: | |||
</pre> | </pre> | ||
< | <pre> | ||
) | |||
Якщо написано <code>powershell.exe</code>, це часто означає Windows PowerShell 5.1.;<div style="background:#f6ffed;border-left:6px solid #27ae60;padding:14px 18px;margin:16px 0;border-radius:8px;"> | |||
PowerShell 7 | * не замінює повноцінну backend-мову для великих сервісів; | ||
* Windows PowerShell і PowerShell 7 мають різну сумісність; | |||
* modules можуть бути platform-specific; | |||
* scripts можуть бути небезпечними без review; | |||
* execution policy не є собою повним захистом; | |||
* секрети потрібно зберігати правильно; | |||
* production automation потребує тестів, логів і least privilege.;== XML == | |||
</pre> | </pre> | ||
$items += "four" | |||
== Splatting == | == Splatting == | ||
* автора; | |||
* popularity; | |||
* source repository; | |||
* license; | |||
* останнє актуалізація; | |||
* залежності; | |||
* security; | |||
* чи trusted repository.;<pre> | |||
} | |||
Start-Transcript -Path .\run.log | |||
</pre> | </pre> | ||
</pre> | </pre> | ||
<pre> | |||
<pre> | |||
powershell.exe | |||
</pre> | </pre> | ||
<code>Sort-Object</code> сортує.; # Використовувати <code>[CmdletBinding()]</code> для складних functions.; Основна ідея | |||
* якщо папка вже існує — не помилка; | |||
* якщо сервіс уже запущений — не запускати зайве; | |||
* якщо користувач системи уже створений — оновити або пропустити.; * '''PowerShell Gallery''' — репозиторій PowerShell-модулів і scripts.;<code>ForEach-Object</code> виконує дію для кожного об’єкта pipeline.; PowerShell підтримує роботу <code>-WhatIf</code> для багатьох destructive commands.;== PowerShell і C#/.NET == | |||
Get-Command *Service* | |||
</div> | |||
[Parameter(Mandatory)] | |||
Get-ChildItem | |||
Code signing сприяє підтвердити, що script походить із довіреного джерела й не був змінений.; # Явно вказувати <code>pwsh</code> у CI/CD.; * '''PSCredential''' — тип для зберігання credentials.; $data | ConvertTo-Json -Depth 10 | |||
<code> | == PowerShell Gallery == | ||
} | ConvertTo-Json | |||
На Windows можна використовувати: | |||
Краще використовувати: | |||
} | } | ||
< | == CSV == | ||
PowerShell має сильну вбудовану help-систему.; * '''Idempotency''' — повторний запуск script не створює небажаних змін.;<ref>https://learn.microsoft.com/en-us/lifecycle/products/powershell</ref> | |||
</pre> | </pre> | ||
Приклад: | Приклад: | ||
Timeout = 30 | |||
[[Категорія:PowerShell]] | |||
<pre> | <pre> | ||
<pre> | |||
[[Категорія:Scripting]] | |||
Get-Process | Select-Object -First 10 | |||
PowerShell часто застосовується в DevOps.; CSV часто застосовують, коли потрібно для звітів, імпорту/експорту й адміністрування.; * '''WhatIf''' — режим попереднього перегляду дії без виконання.; '''Для документації:''' у production краще писати конкретно: PowerShell 7.6 LTS або Windows PowerShell 5.1.; Az | |||
<code>[switch]</code> — boolean-like параметр.; * '''Objects pipeline''' — pipeline, який передає об’єкти, а не лише текст.; * '''Least privilege''' — принцип мінімально необхідних прав.; Приклади: | |||
Write-Verbose "Generating report for $UserName" | |||
PowerShell має змогу працювати з XML.; * build; | |||
* test; | |||
* deploy; | |||
* Azure automation; | |||
* artifact packaging; | |||
* release validation.; Приклад: | |||
'''Cmdlet''' — основна команда PowerShell.; Encoding = "utf8" | |||
У класичному shell команди часто передають текст.;[[Категорія:Пояснення термінів]] | |||
param( | |||
Але credential handling усе одно потребує обережності.;</pre> | |||
Скорочено: | |||
'''істотно:''' не слід радити “без ускладнень поставити Unrestricted” як стандартне рішення для бізнесу.;== Install-Module == | |||
Приклад: | |||
</pre> | |||
Double quotes підставляють змінні.; * '''Windows PowerShell''' — стара реліз PowerShell 5.1 на .NET Framework.;</div> | |||
try { | |||
* '''PowerShell''' — shell, scripting language і automation framework.; Receive-Job $job | |||
== Джерела == | |||
Import-Module Pester | |||
<pre> | <pre> | ||
Invoke-Command -ComputerName Server01 -ScriptBlock { | |||
Set-Content | |||
</pre> | |||
<pre> | |||
PowerShell змінні можуть містити: | |||
Get-Service | ?;== Switch parameters == | |||
<code>$ErrorActionPreference</code> визначає поведінку non-terminating errors.; актуалізація: | |||
* потрібна велика backend-система; | |||
* потрібен web API як production service; | |||
* потрібна AI/data science програмний пакет; | |||
* задача краще вирішується SQL; | |||
* потрібен portable Unix shell script; | |||
* команда не знає PowerShell; | |||
* потрібна складна application architecture; | |||
* script стає настільки великим, що краще перейти на C#, Python або Go.; # Використовувати SecretManagement або vault.; param( | |||
'''PowerShell DSC''' — Desired State Configuration.; ) | |||
PowerShell scripts можна підписувати.; Документація PowerShell містить окремий розділ Deploy і PowerShell Gallery.;== Головна ідея == | |||
Доступ: | |||
Для серйозної автоматизації PowerShell scripts теж потрібно тестувати.; $params = @{ | |||
== Cmdlets == | |||
Invoke-ScriptAnalyzer -Path .\MyScript.ps1 | |||
Azure PowerShell застосовується для: | |||
[[Категорія:Azure]] | |||
</pre> | </pre> | ||
[[Категорія:CI/CD]] | |||
Приклади: | |||
<div style="background:#eef6ff;border-left:6px solid #2f80ed;padding:14px 18px;margin:16px 0;border-radius:8px;"> | |||
* запускати scripts без розуміння; | |||
* ігнорувати errors; | |||
* не використовувати <code>-ErrorAction Stop</code> там, де потрібен catch; | |||
* зберігати passwords у plain text; | |||
* використовувати <code>Write-Host</code> замість pipeline output; | |||
* плутати Windows PowerShell 5.1 і PowerShell 7; | |||
* не вказувати encoding; | |||
* не тестувати scripts; | |||
* не логувати scheduled tasks; | |||
* не перевіряти modules із Gallery; | |||
* використовувати aliases у production scripts; | |||
* не використовувати <code>-WhatIf</code> перед destructive діями.; Advanced function використовує <code>[CmdletBinding()]</code>.; Stop-Transcript | |||
PowerShell — один із найсильніших інструментів для automation, адміністрування й DevOps, особливо в Microsoft-екосистемі.; PowerShell jobs дозволяють виконувати задачі у фоні.; # Тестувати modules через Pester.; PowerShell 7.5 підтримується до 10 листопада 2026 року, а PowerShell 7.4 LTS — додатково до 10 листопада 2026 року.; Конвертація: | |||
Get-Process | Sort-Object CPU -Descending | |||
Get-ChildItem -Path C:\Logs -Filter *.log | | |||
[int]$Limit = 100, | |||
== Microsoft Graph PowerShell == | |||
На Linux/macOS PowerShell корисний для: | |||
} | |||
[[Категорія:Automation]] | |||
Get-Service | Where-Object Status -eq "Running" | |||
<pre> | <pre> | ||
<pre> | <pre> | ||
finally { | |||
'''PowerShell Remoting''' надає можливість виконувати команди на віддалених машинах.;== Strings == | |||
ConvertTo-Json | ConvertTo-Json | ||
== Parameters == | |||
Get-ExecutionPolicy | |||
Це істотно в scripts, CI/CD і документації.;== Коли PowerShell особливо корисний == | |||
== Sort-Object == | |||
Обмеження: | |||
<pre> | <pre> | ||
У сучасних cloud environments часто використовують Microsoft Graph і Entra ID modules.; * '''Module''' — пакет PowerShell-команд і функцій.;<pre> | |||
</pre> | </pre> | ||
== Objects pipeline == | |||
== | * configuration management; | ||
* server baseline; | |||
* compliance; | |||
* repeatable environments; | |||
* infrastructure automation.; офіційно затверджений GitHub repository описує PowerShell як cross-platform automation and configuration tool/framework for Windows, Linux and macOS.;== PowerShell і Bash == | |||
* strings; | |||
* numbers; | |||
* arrays; | |||
* hashtables; | |||
* objects; | |||
* script blocks; | |||
* credentials; | |||
* command results.; Connect-AzAccount | |||
} | |||
PowerShell зручний для REST API.; Update-Module -Name Pester | |||
$data | Where-Object Department -eq "Sales" | |||
Для великих масивів часте <code>+=</code> має змогу бути повільним.;</pre> | |||
Головна особливість PowerShell — pipeline об’єктів.; Приклад: | |||
Для scheduled scripts logging особливо важливий.;== Безпека PowerShell scripts == | |||
</pre> | |||
</ | </pre> | ||
-ContentType "application/json" | |||
Приклад: | Приклад: | ||
== Cross-platform PowerShell == | |||
<pre> | |||
<pre> | |||
<pre> | |||
<pre> | <pre> | ||
Офіційна документація Microsoft описує PowerShell як product documentation для встановлення, використання, прикладів scripts, deployment, PowerShell Gallery і module reference.; PowerShell scripts часто запускають за розкладом.; Python краще для складнішої програмної логіки, data science і AI.; Microsoft Graph PowerShell SDK застосовується для Microsoft 365 і Graph API.; Get-ADGroupMember | |||
Enabled = $true | |||
Splatting робить довгі команди читабельнішими.; PowerShell не є собою ERP-системою.;== Типові помилки в PowerShell == | |||
<pre> | <pre> | ||
- name: Run PowerShell script | |||
Remove-Item | |||
<code>Select-Object</code> вибирає properties.;<ref>https://github.com/PowerShell/PowerShell</ref> | |||
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock { | |||
$isEnabled = $true | |||
== Desired State Configuration == | |||
|- | |||
| '''PowerShell''' || system administration, Microsoft ecosystem, shell automation | |||
|- | |||
| '''Python''' || general-purpose programming, data, AI, backend, scripting | |||
|} | |||
<pre> | <pre> | ||
== Hashtables == | |||
<pre> | Такий стиль робить команди більш передбачуваними.;<pre> | ||
* -Verbose; | !;<pre> | ||
PowerShell scripts можуть бути дуже потужними, з цієї причини потрібна обережність.; '''PSScriptAnalyzer''' — статичний аналізатор PowerShell-коду.; * -Verbose; | |||
* -Debug; | * -Debug; | ||
* -ErrorAction; | * -ErrorAction; | ||
* -WhatIf; | * -WhatIf; | ||
* -Confirm.; | * -Confirm.; додатково можна брати перші або останні записи: | ||
} | |||
== PowerShell в Azure Pipelines == | |||
PowerShell найкраще використовувати там, де потрібна швидка, контрольована й повторювана автоматизація процесів: від локальних scripts до enterprise DevOps і Microsoft cloud administration.; * '''PowerShell 7''' — сучасна cross-platform реліз PowerShell.; New-Item | |||
Це істотно для: | |||
'''Проста аналогія:''' PowerShell — це не без ускладнень командний рядок.;== Credentials == | |||
</pre> | |||
Приклад для кількох серверів: | |||
Copy-Item | |||
Get-Content @params | |||
* CI/CD scripts; | |||
* deployment; | |||
* infrastructure automation; | |||
* Azure pipelines; | |||
* GitHub Actions; | |||
* build scripts; | |||
* release scripts; | |||
* packaging; | |||
* environment setup; | |||
* secrets retrieval; | |||
* smoke tests.; Add-Numbers 2 3 | Should -Be 5 | |||
Для бізнес-звітності ERP краще використовувати спеціалізований reporting layer, але PowerShell має змогу допомогти з технічними export/import задачами.; # Перевіряти версію PowerShell і modules.;<pre> | |||
== Where-Object == | |||
Перед встановленням модуля потрібно перевіряти: | |||
Приклад: | |||
== PowerShell і Python == | |||
PowerShell добре функціонує з JSON.; завдяки наявності <code>Get-Command</code>користувачі можуть знаходити команди.; Hashtable: | |||
* адміністрування Windows; | |||
* керування файлами й процесами; | |||
* автоматизації серверів; | |||
* CI/CD; | |||
* Azure automation; | |||
* Microsoft 365 administration; | |||
* роботи з REST API; | |||
* обробки JSON, CSV, XML; | |||
* керування сервісами; | |||
* конфігурація систем; | |||
* deployment scripts; | |||
* DevOps tasks; | |||
* звітів і audit; | |||
* security automation.; DSC застосовується для: | |||
catch { | |||
[[Категорія:Windows]] | |||
== Active Directory == | |||
== PowerShell Remoting == | |||
Змінні в PowerShell починаються з <code>$</code>.;== PowerShell і API K2 ERP == | |||
Це корисно для паралельного адміністрування.; Його сила — cmdlets, objects pipeline, modules, remoting і тісна інтеграційні функціональні можливості з Microsoft-екосистемою.; * <code>Write-Verbose</code> — verbose stream.; Write-Host $_.FullName | |||
Invoke-RestMethod ` | |||
<pre> | <pre> | ||
Приклад: | Приклад: | ||
<pre> | <pre> | ||
== Select-Object == | |||
* transcript; | |||
* structured logs; | |||
* Start-Transcript; | |||
* Write-Information; | |||
* custom log files; | |||
* Windows Event Log; | |||
* SIEM integration; | |||
* CI/CD logs.; * '''Cmdlet''' — команда PowerShell у форматі Verb-Noun.; Get-Help Get-Process | |||
== Invoke-Command == | |||
PowerShell особливо корисний для: | |||
* unit tests; | |||
* script tests; | |||
* module tests; | |||
* infrastructure tests; | |||
* CI/CD; | |||
* regression tests.;</pre> | |||
PowerShell можна використовувати для технічної звітності: | |||
== Error handling == | |||
} | |||
</pre> | |||
ключовий компонент: | |||
<pre> | <pre> | ||
<pre> | </pre> | ||
PowerShell потужний, з цієї причини його потрібно контролювати й моніторити.; PowerShell дуже поширений у Microsoft 365 administration.; Встановлення модуля: | |||
* [[C Sharp]] | |||
* [[Go]] | |||
* [[Python]] | |||
* [[Розробка в K2 ERP]] | |||
* [[Тестування коду]] | |||
* [[API K2 ERP]] | |||
* [[Інтеграції K2 ERP]] | |||
* [[Звітність K2 ERP]] | |||
* [[GitHub Copilot]] | |||
* [[Cursor]] | |||
* [[Tabnine]] | |||
* [[Retrieval-Augmented Generation]] | |||
* [[Великі мовні моделі]] | |||
* [[GPT]] | |||
* [[Claude Models]] | |||
* [[Штучний інтелект]] | |||
* [[Генеративний AI]] | |||
} | |||
* [https://learn.microsoft.com/en-us/powershell/ Microsoft Learn — PowerShell Documentation] | |||
* [https://github.com/PowerShell/PowerShell PowerShell GitHub Repository] | |||
* [https://github.com/PowerShell/PowerShell/releases PowerShell GitHub Releases] | |||
* [https://learn.microsoft.com/en-us/powershell/scripting/install/install-powershell-on-windows?view=powershell-7.6 Microsoft Learn — Install PowerShell 7 on Windows] | |||
* [https://learn.microsoft.com/uk-ua/powershell/scripting/how-to-use-docs?view=powershell-7.6 Microsoft Learn — How to use PowerShell documentation] | |||
* [https://learn.microsoft.com/en-us/lifecycle/products/powershell Microsoft Lifecycle — PowerShell] | |||
* [https://github.com/MicrosoftDocs/PowerShell-Docs/blob/main/reference/docs-conceptual/install/PowerShell-Support-Lifecycle.md PowerShell Support Lifecycle] | |||
* [https://devblogs.microsoft.com/powershell/announcing-powershell-7-5-ga/ Microsoft PowerShell Blog — PowerShell 7.5 GA] | |||
* [https://www.powershellgallery.com/ PowerShell Gallery] | |||
* [https://pester.dev/ Pester] | |||
* [https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable Microsoft Learn — Everything you wanted to know about hashtables] | |||
* [https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-scriptblock Microsoft Learn — Everything you wanted to know about script blocks] | |||
* [https://www.mediawiki.org/wiki/Help:Formatting MediaWiki — Help:Formatting] | |||
* [https://www.mediawiki.org/wiki/Help:Links MediaWiki — Help:Links] | |||
'''Module''' — пакет PowerShell-коду.; Для cross-platform agents краще використовувати <code>pwsh</code>, а не Windows PowerShell.; У production scripts це має змогу допомогти не пропустити помилки.;<pre> | |||
Cmdlets мають стиль: | |||
Приклад: | |||
PowerShell має різні output streams.; * '''Execution Policy''' — політика запуску scripts.;== Code signing == | |||
Describe "Calculator" { | |||
* cloud automation; | |||
* JSON/API scripts; | |||
* DevOps; | |||
* CI/CD; | |||
* Azure; | |||
* Microsoft 365; | |||
* cross-platform tooling; | |||
* automation around files; | |||
* reporting.;<ref>https://learn.microsoft.com/en-us/powershell/</ref> | |||
* Windows; | |||
* Linux; | |||
* macOS.;</pre> | |||
<pre> | |||
< | <pre> | ||
< | Single quotes залишають текст як є собою.;<ref>https://learn.microsoft.com/en-us/shows/it-ops-talk/how-to-install-powershell-7</ref> | ||
* functions; | |||
* cmdlets; | |||
* aliases; | |||
* variables; | |||
* classes; | |||
* formats; | |||
* types; | |||
* nested modules.; function Get-UserReport { | |||
== | Типи параметрів допомагають робити scripts надійнішими.;== Хороші практики == | ||
<pre> | <pre> | ||
* не запускати незнайомі scripts без перевірки; | |||
* не вставляти команди з інтернету без розуміння; | |||
* не зберігати passwords у коді; | |||
* використовувати least privilege; | |||
* логувати важливі дії; | |||
* підписувати production scripts; | |||
* обмежувати доступ до modules; | |||
* перевіряти dependencies; | |||
* використовувати code review.;== Secrets == | |||
* список файлів; | |||
* стан сервісів; | |||
* audit users; | |||
* disk usage; | |||
* installed modules; | |||
* статус backup; | |||
* API responses; | |||
* CSV exports.; XML досі часто зустрічається в Windows, legacy systems і enterprise configs.; * Task Scheduler; | |||
* Scheduled Jobs; | |||
* Scheduled Tasks; | |||
* Azure Automation; | |||
* CI/CD schedules.; $xml.configuration.appSettings.add | |||
PowerShell і Python часто доповнюють одне одного.; * Windows administration; | |||
* Microsoft 365; | |||
* Azure; | |||
* DevOps; | |||
* CI/CD; | |||
* server automation; | |||
* file operations; | |||
* registry operations; | |||
* service management; | |||
* CSV/JSON/XML processing; | |||
* REST API automation; | |||
* scheduled tasks; | |||
* audit reports; | |||
* deployment scripts; | |||
* troubleshooting; | |||
* інтеграцій.;== pwsh == | |||
$name = "PowerShell" | |||
Виклик: | |||
Get-Module | |||
Для великого production-сервісу або library — C# має змогу бути кращим.;</pre> | |||
Get-Process | Select-Object Name, Id, CPU | |||
run: | | |||
} | } | ||
Enter-PSSession -ComputerName Server01 | |||
</pre> | </pre> | ||
<pre> | |||
<div style="background:#eef6ff;border-left:6px solid #2f80ed;padding:14px 18px;margin:16px 0;border-radius:8px;"> | |||
Приклад: | |||
if ($Force) { | |||
function Get-Greeting { | function Get-Greeting { | ||
== | У PowerShell команди передають .NET objects.; Jobs корисні для довгих операцій, але в сучасних сценаріях додатково використовують runspaces, ThreadJob або CI/CD runners.; Shell !!;<pre> | ||
== Enter-PSSession | <div style="background:#fff7e6;border-left:6px solid #f2994a;padding:14px 18px;margin:16px 0;border-radius:8px;"> | ||
$ErrorActionPreference = "Stop" | |||
Приклад: | |||
Get-ADUser | |||
Сценарії: | |||
== Working with files == | |||
Install-Module Pester | |||
shell: pwsh | |||
Get-Service | |||
</div> | |||
$PSVersionTable | |||
Для scheduled scripts істотно логувати результат і помилки, бо користувач системи не бачить інтерактивний вивід.;[[Категорія:Інтеграції]] | |||
Виклик: | |||
істотно явно вказувати <code>pwsh</code>, якщо потрібен PowerShell 7.; REST API + PowerShell — популярна пара для інтеграцій і automation.; PowerShell використовують для: | |||
PowerShell і Bash мають різну філософію.; Не варто запускати все від Administrator, якщо достатньо звичайного користувача.;<pre> | |||
істотно: не всі errors за замовчуванням terminating.;<ref>https://learn.microsoft.com/en-us/powershell/</ref> | |||
Приклади: | |||
Приклад: | |||
</pre> | |||
== Logging == | |||
Приклад: | |||
Для automation краще створювати окремі service accounts із мінімальними правами.; PowerShell особливо зручний у Windows і Azure environments.; # Використовувати <code>-WhatIf</code> для destructive operations.;</pre> | |||
!; * '''Enter-PSSession''' — інтерактивна remote session.; Сильні сторони | |||
</pre> | </pre> | ||
Get- | [switch]$Force | ||
Підходи: | |||
</div> | |||
== PowerShell у Linux/macOS == | |||
Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | |||
== Jobs == | |||
== Azure PowerShell == | |||
Приклад сценарію: | |||
Інтерактивна remote session: | |||
Idempotent scripts безпечніші для deployment і configuration.;[[Категорія:Microsoft]] | |||
* ''' | Modules допомагають організувати scripts у reusable components.; * '''Pester''' — testing framework для PowerShell.;</pre> | ||
'''Idempotency''' — властивість script, коли повторний запуск не ламає систему й не створює дублікати.; * '''Invoke-Command''' — cmdlet для виконання script block локально або віддалено.; Status -eq "Running" | |||
<pre> | |||
{| class="wikitable" | |||
Приклад: | |||
Get-Greeting -Name "Anna" | |||
[switch]$Force | [switch]$Force | ||
<div style="background:#fff0f0;border-left:6px solid #eb5757;padding:14px 18px;margin:16px 0;border-radius:8px;"> | |||
</pre> | |||
== Script Analyzer == | |||
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser | |||
<pre> | |||
[[Категорія:Безпека]] | |||
Добра практика — читати help перед запуском незнайомої команди.; * '''Hashtable''' — key-value структура.;<pre> | |||
Такі scripts корисні для адміністрування, але критичні операції мають бути захищені правами доступу й логуванням.;<pre> | |||
Поширені помилки: | |||
== Актуальна реліз == | |||
== Variables == | |||
</pre> | |||
Advanced functions підтримують common parameters, як ілюстрація: | |||
./build.ps1 | |||
Сценарії: | |||
New-Item | |||
} | |||
"Hello, $Name" | |||
Remove-Item | |||
[string]$UserName | |||
Import-Module Az | |||
Get-Process | |||
-Body $body ` | |||
Bash сильний для Unix scripting і текстових команд.;</pre> | |||
<div style="background:#fff7e6;border-left:6px solid #f2994a;padding:14px 18px;margin:16px 0;border-radius:8px;"> | <div style="background:#fff7e6;border-left:6px solid #f2994a;padding:14px 18px;margin:16px 0;border-radius:8px;"> | ||
У власних advanced functions можна підтримувати <code>ShouldProcess</code>, щоб додати <code>-WhatIf</code> і <code>-Confirm</code>.;<pre> | |||
</pre> | |||
-Uri "https://api.example.com/items" ` | |||
* objects pipeline; | |||
* cmdlets; | |||
* modules; | |||
* PowerShell Gallery; | |||
* remoting; | |||
* cross-platform PowerShell 7; | |||
* Windows PowerShell 5.1 compatibility; | |||
* JSON/CSV/XML; | |||
* REST API; | |||
* Azure і Microsoft 365; | |||
* Pester; | |||
* PSScriptAnalyzer; | |||
* CI/CD; | |||
* automation scripts; | |||
* .NET integration.; Краще розуміти політику, підпис scripts і корпоративні правила.; New-ADUser | |||
<pre> | |||
</pre> | |||
* отримати token; | |||
* викликати endpoint; | |||
* зберегти JSON; | |||
* сформувати CSV-звіт; | |||
* надіслати результат адміністратору.; Install-Module -Name Pester -Scope CurrentUser | |||
Масив: | |||
param( | |||
[string]$Path, | |||
{{SEO|title=PowerShell — shell, scripting language, automation, objects pipeline, modules, remoting, DevOps і адміністрування Windows/Linux/macOS|description=PowerShell — Wiki-стаття про кросплатформений shell і scripting language від Microsoft для автоматизації, адміністрування, DevOps, CI/CD, Azure, Microsoft 365, Windows Server, Linux/macOS, objects pipeline, cmdlets, modules, remoting, jobs, error handling, security, execution policy, secrets, logging, testing, Pester, PowerShell Gallery, PowerShell 7.6 LTS і Windows PowerShell 5.1.|keywords=PowerShell, PowerShell 7.6, PowerShell 7, Windows PowerShell, PowerShell Core, Microsoft PowerShell, PowerShell scripting, PowerShell automation, cmdlets, objects pipeline, PowerShell modules, PowerShell remoting, PowerShell Gallery, Pester, PowerShell DSC, Azure PowerShell, Microsoft Graph PowerShell, Windows administration, DevOps PowerShell, CI/CD PowerShell, PowerShell security, execution policy, PowerShell scripts, pwsh|alternativeTo=ручне адміністрування серверів; batch scripts; cmd.exe; VBScript; ручні операції в Windows GUI; повторювані DevOps-задачі без автоматизації; shell без object pipeline; адміністрування Microsoft 365 без скриптів; ручне керування файлами, сервісами й реєстром}} | {{SEO|title=PowerShell — shell, scripting language, automation, objects pipeline, modules, remoting, DevOps і адміністрування Windows/Linux/macOS|description=PowerShell — Wiki-стаття про кросплатформений shell і scripting language від Microsoft для автоматизації, адміністрування, DevOps, CI/CD, Azure, Microsoft 365, Windows Server, Linux/macOS, objects pipeline, cmdlets, modules, remoting, jobs, error handling, security, execution policy, secrets, logging, testing, Pester, PowerShell Gallery, PowerShell 7.6 LTS і Windows PowerShell 5.1.|keywords=PowerShell, PowerShell 7.6, PowerShell 7, Windows PowerShell, PowerShell Core, Microsoft PowerShell, PowerShell scripting, PowerShell automation, cmdlets, objects pipeline, PowerShell modules, PowerShell remoting, PowerShell Gallery, Pester, PowerShell DSC, Azure PowerShell, Microsoft Graph PowerShell, Windows administration, DevOps PowerShell, CI/CD PowerShell, PowerShell security, execution policy, PowerShell scripts, pwsh|alternativeTo=ручне адміністрування серверів; batch scripts; cmd.exe; VBScript; ручні операції в Windows GUI; повторювані DevOps-задачі без автоматизації; shell без object pipeline; адміністрування Microsoft 365 без скриптів; ручне керування файлами, сервісами й реєстром}} | ||
{| class="wikitable" | |||
Доступ: | |||
PowerShell має тип <code>PSCredential</code>.;<ref>https://github.com/PowerShell/PowerShell/releases</ref> | |||
</pre> | |||
Але для класичних Unix tasks Bash, zsh, Python або Go можуть бути природнішими.; # Писати повні cmdlet names, а не aliases.; Це корисно для quick diagnostics, reports і audit scripts.; Приклад: | |||
Приклад: | |||
# Використовувати PowerShell 7.6 LTS для нових cross-platform scripts.; '''Практична порада:''' не використовуйте <code>Write-Host</code> для даних, які мають піти далі в pipeline.;<pre> | |||
Test-Path | |||
</pre> | </pre> | ||
Get- | PowerShell побудований на .NET і має змогу працювати з .NET objects.; Корисно для пошуку cmdlets, functions, aliases і applications.; Приклад: | ||
Get-Process | |||
Головна ідея PowerShell — автоматизувати рутинні адміністративні й інженерні задачі через зрозумілу командну мову.; * '''PowerShell 7+''' — сучасна кросплатформена реліз, функціонує на сучасному .NET і запускається як <code>pwsh</code>.; Це надає можливість працювати на віддаленій машині майже як локально.; Invoke-WebRequest | |||
Environment = "Production" | |||
PowerShell 7 можна встановлювати поруч із Windows PowerShell 5.1.; pwsh | |||
Get-Help Get-Process -Full | |||
$cred = Get-Credential | |||
Invoke-RestMethod | Invoke-RestMethod | ||
Не варто зберігати secrets у plain text scripts.; $items = @("one", "two", "three") | |||
Add-Content | |||
Get-Help Get-Process -Examples | |||
Set-ADUser | |||
== Functions == | |||
<pre> | <pre> | ||
Write- | Write-Error "Cannot read file: $_" | ||
$data | Export-Csv .\sales-users.csv -NoTypeInformation | |||
* <code>Write-Output</code> — output pipeline.;== JSON == | |||
== Modules == | |||
Правила: | |||
|- | |||
| '''PowerShell''' || pipeline об’єктів, cmdlets, .NET objects, Microsoft ecosystem | |||
|- | |||
| '''Bash''' || текстовий pipeline, Unix tools, простота для POSIX-систем | |||
|} | |||
є собою дві важливі лінії: | |||
<pre> | |||
== | PowerShell GitHub repository описує PowerShell як оптимізований для structured data, зокрема JSON, CSV, XML, REST APIs і object models.; '''Коротко:''' PowerShell — це shell для автоматизації.;== REST API == | ||
Приклад: | Приклад: | ||
< | * passwords; | ||
</ | * tokens; | ||
* API keys; | |||
* certificates; | |||
* connection strings; | |||
* credentials.; # Додавати <code>param()</code> і типи параметрів.; Remoting корисний для: | |||
== Security logging і audit == | |||
== ForEach-Object == | |||
Станом на травень 2026 року актуальна LTS-гілка — '''PowerShell 7.6 LTS'''.; Поведінка модулів і сумісність можуть відрізнятися.; Можна звертатися до властивостей об’єкта: Name, Id, CPU, Path, Status.;<pre> | |||
== | == Pester == | ||
* викликати .NET classes; | |||
* працювати з assemblies; | |||
* створювати objects; | |||
* використовувати .NET APIs; | |||
* писати binary modules на C#.; * '''pwsh''' — виконуваний файл PowerShell 7+.; * '''ScriptBlock''' — блок PowerShell-коду як значення.; * <code>Write-Debug</code> — debug.; На GitHub Releases додатково вказано релізи PowerShell 7.6.1 і 7.5.6.; name = "Test" | |||
Get-AzResourceGroup | |||
== Advanced functions == | |||
'''PowerShell Gallery''' — офіційно затверджений репозиторій PowerShell-модулів і scripts.; Execution Policy не є собою повноцінною security boundary.; Приклад: | |||
<pre> | <pre> | ||
Path = "C:\Temp\report.txt" | |||
} | } | ||
Для швидкої автоматизації — PowerShell.;</pre> | |||
Приклад: | |||
<pre> | <pre> | ||
Set-Location | |||
</pre> | |||
Move-Item | |||
Приклад: | Приклад: | ||
<pre> | <pre> | ||
$config ["Environment"] | |||
Microsoft Lifecycle показує, що PowerShell 7.6 LTS стартував 18 березня 2026 року й підтримується до 14 листопада 2028 року.; Ідея: описати бажаний стан системи, а не вручну виконувати всі кроки.;</div> | |||
== Idempotency == | |||
</pre> | |||
це кросплатформений shell, scripting language і automation framework від Microsoft; додатково реалізовано автоматизації задач, DevOps, CI/CD, роботи з Windows, Linux, macOS, Azure, Microsoft 365, API, файлами, процесами, сервісами й structured data виступає ключовою рисою адміністрування систем забезпечується через '''PowerShell'''.;</pre> | |||
PowerShell сильний для structured data й Microsoft automation.; Для даних використовуйте output, для повідомлень — verbose або information streams.; '''Least privilege''' означає: script має мати тільки ті права, які йому справді потрібні.; # Аналізувати код через PSScriptAnalyzer.;== Get-Help == | |||
як ілюстрація, Windows-specific modules можуть залежати від Windows APIs.; # Логувати scheduled і production runs.; $json | ConvertFrom-Json | |||
$count = 10 | |||
It "adds numbers" { | |||
Тут <code>Get-Process</code> повертає об’єкти процесів, а не без ускладнень текстову таблицю.; Важливі механізми: | |||
Приклади: | |||
</pre> | </pre> | ||
* users; | |||
* groups; | |||
* devices; | |||
* Teams; | |||
* SharePoint; | |||
* Entra ID; | |||
* reports; | |||
* permissions; | |||
* automation.; # Документувати scripts і приклади запуску.; Приклад: | |||
'''Pester''' — популярний testing framework для PowerShell.;== Execution Policy == | |||
<pre> | <pre> | ||
) | |||
Verb-Noun | |||
<pre> | <pre> | ||
Microsoft Learn пояснює, що PowerShell 7 є собою cross-platform, open-source і встановлюється side-by-side з Windows PowerShell 5.1.; Це істотно для безпечної автоматизації.; } | |||
'''Splatting''' надає можливість передавати параметри через hashtable.; * '''Remoting''' — віддалене виконання PowerShell-команд.; Get-Content -Path $Path -ErrorAction Stop | |||
PowerShell 7 функціонує на: | |||
</div> | |||
$ | Але треба розуміти наслідки: script має змогу зупинитися там, де раніше продовжував роботу.; PowerShell має змогу бути невдалим вибором, якщо: | ||
$response.users | Select-Object id, name | |||
</pre> | </pre> | ||
"Hello, $name" | |||
} | } | ||
Get-Process | |||
</pre> | Where-Object LastWriteTime -lt (Get-Date).AddDays(-30) | ||
</pre> | |||
== Enter-PSSession == | |||
PowerShell має змогу викликати REST API. | |||
Поточна версія на 20:18, 8 травня 2026
DSC має окрему історію версій і сценаріїв, з цієї причини для production потрібно перевіряти актуальну документацію під конкретну платформу.;== $ErrorActionPreference ==
Пояснення термінів
PowerShell має cmdlets для файлів:
Get-Content * enterprise; * production scripts; * security policies; * regulated environments; * deployment automation.; Сценарії:
PowerShell відрізняється від багатьох shell тим, що передає між командами не без ускладнень текст, а об’єкти.;== Коли PowerShell має змогу бути невдалим вибором ==
[CmdletBinding()]
PowerShell у DevOps
PowerShell має сильну систему parameters.; Додавання:
$data = Import-Csv .\users.csv
Він не веде обліковий облік, не проводить документи й не керує складом сам по собі.;
PowerShell і формування звітів
Pester корисний для:
<pre> Функція: <pre> PowerShell має single-quoted і double-quoted strings.; [xml]$xml = Get-Content .\config.xml Get-ChildItem <pre>
$items [0]
Azure PowerShell — модулі для керування Azure.; У GitHub Actions можна використовувати PowerShell.; # Обробляти помилки через try/catch.; Інструмент !!;
<pre> Get-Service <code>$_</code> означає поточний об’єкт pipeline.; * '''PSScriptAnalyzer''' — статичний аналізатор PowerShell-коду.; Але PowerShell не повинен обходити бізнес-логіку ERP, права доступу або audit.; * <code>Write-Warning</code> — warning.;<ref>https://github.com/PowerShell/PowerShell</ref> [[Категорія:Адміністрування]] Це надає можливість: ) У корпоративному середовищі PowerShell повинен бути видимим для security teams.;
[string]$Name
- deployment scripts;
- backup scripts;
- automation around Windows services;
- log collection;
- scheduled exports;
- API calls;
- monitoring checks;
- CI/CD;
- адміністративних задач;
- integration scripts;
- генерації технічних звітів.; Remove-Item .\old-files\* -WhatIf
PowerShell краще для адміністрування Windows/Microsoft 365/Azure.;Invoke-Command виконує script block локально або віддалено.; PowerShell дуже зручний для CSV.; * SecretManagement — підхід і модулі для роботи з secrets.; * style issues;
- potential bugs;
- security problems;
- deprecated patterns;
- best practice violations.; Краще використовувати collections або pipeline.; *
Write-Host— вивід на екран.; Але не всі modules однаково працюють на всіх платформах.; * Code signing — цифровий підпис scripts.;
Execution Policy — механізм, який контролює запуск scripts у Windows PowerShell/PowerShell.; Exit-PSSession
Сильні сторони:
<code>Where-Object</code> фільтрує об’єкти.;
$config = @{
Invoke-RestMethod
Імпорт:
Приклад:
PowerShell має error handling через try/catch/finally.; * DSC — Desired State Configuration.; Він сприяє знаходити:
PowerShell часто функціонує з secrets:
Remoting потребує правильної безпеки, автентифікації й мережевих налаштувань.; # Не зберігати secrets у scripts.;== Практичний висновок ==
$name = "Anna"
Find-Module Pester
Dry run і WhatIf
Це радше safety feature, яка сприяє запобігти випадковому запуску небажаних scripts.; * Pipeline — передача результатів однієї команди в іншу.; * адміністрування серверів;
- масових змін;
- audit;
- deployment;
- troubleshooting;
- Windows Server;
- hybrid environments.; [Parameter(Mandatory)]
PowerShell automation має логувати результат.;Get-Help показує довідку.; * Splatting — передача параметрів через hashtable.; # Дотримуватися least privilege.; -Method Post `
- SecretManagement module;
- SecretStore;
- Azure Key Vault;
- Windows Credential Manager;
- environment variables;
- CI/CD secret storage;
- managed identities.;== PowerShell і ERP-системи ==
Сучасний PowerShell запускається командою: Windows PowerShell зазвичай запускається як:
- commands
Приклад: У контексті K2 ERP PowerShell має змогу бути корисним для:
Azure Pipelines має PowerShell tasks.;
Write-Verbose "Done"
Get-ChildItem *.log | ForEach-Object {
active = $true
Вихід:
Scheduled jobs і Task Scheduler
Get-AzVM
Least privilege
Приклад:
AD cmdlets зазвичай доступні через RSAT/ActiveDirectory module.; Це пульт керування системою, де команди повертають структуровані об’єкти, а не “кашу” з тексту.; Для catch часто потрібно -ErrorAction Stop.; 'Hello, $name'
Це краще, ніж просити користувача вводити password у plain text.; $body = @{
- script block logging;
- module logging;
- transcription;
- constrained language mode;
- AMSI;
- event logs;
- Defender integration;
- SIEM forwarding.; * Job — фонова задача PowerShell.; Команди:
У корпоративному середовищі встановлення модулів має змогу бути обмежене політиками.;
== Write-Output, Write-Host, Write-Error ==
== Get-Command ==
[[Категорія:Shell]]
Якщо написано <code>pwsh</code>, це PowerShell 7+.; }
== PowerShell у GitHub Actions ==
Приклад:
Під час роботи з PowerShell варто:
== Дивіться додатково ==
}
Команди:
$response = Invoke-RestMethod -Uri "https://api.example.com/users"
Hashtables часто використовують для параметрів, конфігурації, JSON-подібних структур і splatting.; Приклад:
У документації краще писати повну форму, бо вона зрозуміліша.; Приклад:
$job = Start-Job -ScriptBlock {
Windows PowerShell часто застосовується для Active Directory.; PowerShell functions можуть поводитися як cmdlets, якщо правильно описати parameters.; param(
.\script.ps1 -Force
"Force mode enabled"
* resource management;
* automation;
* deployment;
* audit;
* reporting;
* governance.; '''Чому це істотно:''' у PowerShell не потрібно парсити колонки тексту.; компонент має змогу містити:
== PowerShell і Windows PowerShell ==
* '''Windows PowerShell 5.1''' — стара реліз, вбудована у Windows, функціонує на .NET Framework.; * <code>Write-Error</code> — error stream.; $config.Timeout
Приклад:
Це покаже команди, пов’язані із сервісами.;== Arrays ==
Приклад:
) Якщо написано <code>powershell.exe</code>, це часто означає Windows PowerShell 5.1.;<div style="background:#f6ffed;border-left:6px solid #27ae60;padding:14px 18px;margin:16px 0;border-radius:8px;"> * не замінює повноцінну backend-мову для великих сервісів; * Windows PowerShell і PowerShell 7 мають різну сумісність; * modules можуть бути platform-specific; * scripts можуть бути небезпечними без review; * execution policy не є собою повним захистом; * секрети потрібно зберігати правильно; * production automation потребує тестів, логів і least privilege.;== XML ==
$items += "four"
Splatting
- автора;
- popularity;
- source repository;
- license;
- останнє актуалізація;
- залежності;
- security;
- чи trusted repository.;
} Start-Transcript -Path .\run.log
<pre> powershell.exe
Sort-Object сортує.; # Використовувати [CmdletBinding()] для складних functions.; Основна ідея
- якщо папка вже існує — не помилка;
- якщо сервіс уже запущений — не запускати зайве;
- якщо користувач системи уже створений — оновити або пропустити.; * PowerShell Gallery — репозиторій PowerShell-модулів і scripts.;
ForEach-Objectвиконує дію для кожного об’єкта pipeline.; PowerShell підтримує роботу-WhatIfдля багатьох destructive commands.;== PowerShell і C#/.NET ==
Get-Command *Service*
[Parameter(Mandatory)]
Get-ChildItem
Code signing сприяє підтвердити, що script походить із довіреного джерела й не був змінений.; # Явно вказувати pwsh у CI/CD.; * PSCredential — тип для зберігання credentials.; $data | ConvertTo-Json -Depth 10
PowerShell Gallery
} | ConvertTo-Json На Windows можна використовувати: Краще використовувати: }
CSV
PowerShell має сильну вбудовану help-систему.; * Idempotency — повторний запуск script не створює небажаних змін.;[1]
Приклад:
Timeout = 30
<pre> [[Категорія:Scripting]] Get-Process | Select-Object -First 10 PowerShell часто застосовується в DevOps.; CSV часто застосовують, коли потрібно для звітів, імпорту/експорту й адміністрування.; * '''WhatIf''' — режим попереднього перегляду дії без виконання.; '''Для документації:''' у production краще писати конкретно: PowerShell 7.6 LTS або Windows PowerShell 5.1.; Az <code>[switch]</code> — boolean-like параметр.; * '''Objects pipeline''' — pipeline, який передає об’єкти, а не лише текст.; * '''Least privilege''' — принцип мінімально необхідних прав.; Приклади: Write-Verbose "Generating report for $UserName" PowerShell має змогу працювати з XML.; * build; * test; * deploy; * Azure automation; * artifact packaging; * release validation.; Приклад: '''Cmdlet''' — основна команда PowerShell.; Encoding = "utf8" У класичному shell команди часто передають текст.;[[Категорія:Пояснення термінів]] param( Але credential handling усе одно потребує обережності.;
Скорочено:
істотно: не слід радити “без ускладнень поставити Unrestricted” як стандартне рішення для бізнесу.;== Install-Module ==
Приклад:
Double quotes підставляють змінні.; * Windows PowerShell — стара реліз PowerShell 5.1 на .NET Framework.;
try {
- PowerShell — shell, scripting language і automation framework.; Receive-Job $job
Джерела
Import-Module Pester
Invoke-Command -ComputerName Server01 -ScriptBlock {
Set-Content
PowerShell змінні можуть містити:
Get-Service | ?;== Switch parameters ==
<code>$ErrorActionPreference</code> визначає поведінку non-terminating errors.; актуалізація:
* потрібна велика backend-система;
* потрібен web API як production service;
* потрібна AI/data science програмний пакет;
* задача краще вирішується SQL;
* потрібен portable Unix shell script;
* команда не знає PowerShell;
* потрібна складна application architecture;
* script стає настільки великим, що краще перейти на C#, Python або Go.; # Використовувати SecretManagement або vault.; param(
'''PowerShell DSC''' — Desired State Configuration.; )
PowerShell scripts можна підписувати.; Документація PowerShell містить окремий розділ Deploy і PowerShell Gallery.;== Головна ідея ==
Доступ:
Для серйозної автоматизації PowerShell scripts теж потрібно тестувати.; $params = @{
== Cmdlets ==
Invoke-ScriptAnalyzer -Path .\MyScript.ps1
Azure PowerShell застосовується для:
[[Категорія:Azure]]
Приклади:
- запускати scripts без розуміння;
- ігнорувати errors;
- не використовувати
-ErrorAction Stopтам, де потрібен catch; - зберігати passwords у plain text;
- використовувати
Write-Hostзамість pipeline output; - плутати Windows PowerShell 5.1 і PowerShell 7;
- не вказувати encoding;
- не тестувати scripts;
- не логувати scheduled tasks;
- не перевіряти modules із Gallery;
- використовувати aliases у production scripts;
- не використовувати
-WhatIfперед destructive діями.; Advanced function використовує[CmdletBinding()].; Stop-Transcript
PowerShell — один із найсильніших інструментів для automation, адміністрування й DevOps, особливо в Microsoft-екосистемі.; PowerShell jobs дозволяють виконувати задачі у фоні.; # Тестувати modules через Pester.; PowerShell 7.5 підтримується до 10 листопада 2026 року, а PowerShell 7.4 LTS — додатково до 10 листопада 2026 року.; Конвертація:
Get-Process | Sort-Object CPU -Descending
Get-ChildItem -Path C:\Logs -Filter *.log |
[int]$Limit = 100,
Microsoft Graph PowerShell
На Linux/macOS PowerShell корисний для: } Get-Service | Where-Object Status -eq "Running"
<pre>
finally {
'''PowerShell Remoting''' надає можливість виконувати команди на віддалених машинах.;== Strings ==
ConvertTo-Json
== Parameters ==
Get-ExecutionPolicy
Це істотно в scripts, CI/CD і документації.;== Коли PowerShell особливо корисний ==
== Sort-Object ==
Обмеження:
<pre>
У сучасних cloud environments часто використовують Microsoft Graph і Entra ID modules.; * '''Module''' — пакет PowerShell-команд і функцій.;<pre>
Objects pipeline
- configuration management;
- server baseline;
- compliance;
- repeatable environments;
- infrastructure automation.; офіційно затверджений GitHub repository описує PowerShell як cross-platform automation and configuration tool/framework for Windows, Linux and macOS.;== PowerShell і Bash ==
- strings;
- numbers;
- arrays;
- hashtables;
- objects;
- script blocks;
- credentials;
- command results.; Connect-AzAccount
}
PowerShell зручний для REST API.; Update-Module -Name Pester
$data | Where-Object Department -eq "Sales"
Для великих масивів часте+= має змогу бути повільним.;
Головна особливість PowerShell — pipeline об’єктів.; Приклад:
Для scheduled scripts logging особливо важливий.;== Безпека PowerShell scripts ==
-ContentType "application/json"
Приклад:
Cross-platform PowerShell
<pre>
<pre>
<pre>
Офіційна документація Microsoft описує PowerShell як product documentation для встановлення, використання, прикладів scripts, deployment, PowerShell Gallery і module reference.; PowerShell scripts часто запускають за розкладом.; Python краще для складнішої програмної логіки, data science і AI.; Microsoft Graph PowerShell SDK застосовується для Microsoft 365 і Graph API.; Get-ADGroupMember
Enabled = $true
Splatting робить довгі команди читабельнішими.; PowerShell не є собою ERP-системою.;== Типові помилки в PowerShell ==
<pre>
- name: Run PowerShell script
Remove-Item
<code>Select-Object</code> вибирає properties.;<ref>https://github.com/PowerShell/PowerShell</ref>
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock {
$isEnabled = $true
== Desired State Configuration ==
|-
| '''PowerShell''' || system administration, Microsoft ecosystem, shell automation
|-
| '''Python''' || general-purpose programming, data, AI, backend, scripting
|}
<pre>
== Hashtables ==
Такий стиль робить команди більш передбачуваними.;<pre>
!;<pre>
PowerShell scripts можуть бути дуже потужними, з цієї причини потрібна обережність.; '''PSScriptAnalyzer''' — статичний аналізатор PowerShell-коду.; * -Verbose;
* -Debug;
* -ErrorAction;
* -WhatIf;
* -Confirm.; додатково можна брати перші або останні записи:
}
== PowerShell в Azure Pipelines ==
PowerShell найкраще використовувати там, де потрібна швидка, контрольована й повторювана автоматизація процесів: від локальних scripts до enterprise DevOps і Microsoft cloud administration.; * '''PowerShell 7''' — сучасна cross-platform реліз PowerShell.; New-Item
Це істотно для:
'''Проста аналогія:''' PowerShell — це не без ускладнень командний рядок.;== Credentials ==
Приклад для кількох серверів:
Copy-Item
Get-Content @params
- CI/CD scripts;
- deployment;
- infrastructure automation;
- Azure pipelines;
- GitHub Actions;
- build scripts;
- release scripts;
- packaging;
- environment setup;
- secrets retrieval;
- smoke tests.; Add-Numbers 2 3 | Should -Be 5
== Where-Object ==
Перед встановленням модуля потрібно перевіряти:
Приклад:
== PowerShell і Python ==
PowerShell добре функціонує з JSON.; завдяки наявності <code>Get-Command</code>користувачі можуть знаходити команди.; Hashtable:
* адміністрування Windows;
* керування файлами й процесами;
* автоматизації серверів;
* CI/CD;
* Azure automation;
* Microsoft 365 administration;
* роботи з REST API;
* обробки JSON, CSV, XML;
* керування сервісами;
* конфігурація систем;
* deployment scripts;
* DevOps tasks;
* звітів і audit;
* security automation.; DSC застосовується для:
catch {
[[Категорія:Windows]]
== Active Directory ==
== PowerShell Remoting ==
Змінні в PowerShell починаються з <code>$</code>.;== PowerShell і API K2 ERP ==
Це корисно для паралельного адміністрування.; Його сила — cmdlets, objects pipeline, modules, remoting і тісна інтеграційні функціональні можливості з Microsoft-екосистемою.; * <code>Write-Verbose</code> — verbose stream.; Write-Host $_.FullName
Invoke-RestMethod `
<pre>
Приклад:
<pre>
== Select-Object ==
* transcript;
* structured logs;
* Start-Transcript;
* Write-Information;
* custom log files;
* Windows Event Log;
* SIEM integration;
* CI/CD logs.; * '''Cmdlet''' — команда PowerShell у форматі Verb-Noun.; Get-Help Get-Process
== Invoke-Command ==
PowerShell особливо корисний для:
* unit tests;
* script tests;
* module tests;
* infrastructure tests;
* CI/CD;
* regression tests.;
PowerShell можна використовувати для технічної звітності:
Error handling
}
ключовий компонент:
PowerShell потужний, з цієї причини його потрібно контролювати й моніторити.; PowerShell дуже поширений у Microsoft 365 administration.; Встановлення модуля:
- C Sharp
- Go
- Python
- Розробка в K2 ERP
- Тестування коду
- API K2 ERP
- Інтеграції K2 ERP
- Звітність K2 ERP
- GitHub Copilot
- Cursor
- Tabnine
- Retrieval-Augmented Generation
- Великі мовні моделі
- GPT
- Claude Models
- Штучний інтелект
- Генеративний AI
}
- Microsoft Learn — PowerShell Documentation
- PowerShell GitHub Repository
- PowerShell GitHub Releases
- Microsoft Learn — Install PowerShell 7 on Windows
- Microsoft Learn — How to use PowerShell documentation
- Microsoft Lifecycle — PowerShell
- PowerShell Support Lifecycle
- Microsoft PowerShell Blog — PowerShell 7.5 GA
- PowerShell Gallery
- Pester
- Microsoft Learn — Everything you wanted to know about hashtables
- Microsoft Learn — Everything you wanted to know about script blocks
- MediaWiki — Help:Formatting
- MediaWiki — Help:Links
pwsh, а не Windows PowerShell.; У production scripts це має змогу допомогти не пропустити помилки.;
Cmdlets мають стиль:
Приклад:
PowerShell має різні output streams.; * '''Execution Policy''' — політика запуску scripts.;== Code signing ==
Describe "Calculator" {
* cloud automation;
* JSON/API scripts;
* DevOps;
* CI/CD;
* Azure;
* Microsoft 365;
* cross-platform tooling;
* automation around files;
* reporting.;<ref>https://learn.microsoft.com/en-us/powershell/</ref>
* Windows;
* Linux;
* macOS.;
<pre>
Single quotes залишають текст як є собою.;<ref>https://learn.microsoft.com/en-us/shows/it-ops-talk/how-to-install-powershell-7</ref>
* functions;
* cmdlets;
* aliases;
* variables;
* classes;
* formats;
* types;
* nested modules.; function Get-UserReport {
Типи параметрів допомагають робити scripts надійнішими.;== Хороші практики ==
<pre>
* не запускати незнайомі scripts без перевірки;
* не вставляти команди з інтернету без розуміння;
* не зберігати passwords у коді;
* використовувати least privilege;
* логувати важливі дії;
* підписувати production scripts;
* обмежувати доступ до modules;
* перевіряти dependencies;
* використовувати code review.;== Secrets ==
* список файлів;
* стан сервісів;
* audit users;
* disk usage;
* installed modules;
* статус backup;
* API responses;
* CSV exports.; XML досі часто зустрічається в Windows, legacy systems і enterprise configs.; * Task Scheduler;
* Scheduled Jobs;
* Scheduled Tasks;
* Azure Automation;
* CI/CD schedules.; $xml.configuration.appSettings.add
PowerShell і Python часто доповнюють одне одного.; * Windows administration;
* Microsoft 365;
* Azure;
* DevOps;
* CI/CD;
* server automation;
* file operations;
* registry operations;
* service management;
* CSV/JSON/XML processing;
* REST API automation;
* scheduled tasks;
* audit reports;
* deployment scripts;
* troubleshooting;
* інтеграцій.;== pwsh ==
$name = "PowerShell"
Виклик:
Get-Module
Для великого production-сервісу або library — C# має змогу бути кращим.;
Get-Process | Select-Object Name, Id, CPU
run: |
}
Enter-PSSession -ComputerName Server01
<div style="background:#eef6ff;border-left:6px solid #2f80ed;padding:14px 18px;margin:16px 0;border-radius:8px;">
Приклад:
if ($Force) {
function Get-Greeting {
У PowerShell команди передають .NET objects.; Jobs корисні для довгих операцій, але в сучасних сценаріях додатково використовують runspaces, ThreadJob або CI/CD runners.; Shell !!;<pre>
<div style="background:#fff7e6;border-left:6px solid #f2994a;padding:14px 18px;margin:16px 0;border-radius:8px;">
$ErrorActionPreference = "Stop"
Приклад:
Get-ADUser
Сценарії:
== Working with files ==
Install-Module Pester
shell: pwsh
Get-Service
</div>
$PSVersionTable
Для scheduled scripts істотно логувати результат і помилки, бо користувач системи не бачить інтерактивний вивід.;[[Категорія:Інтеграції]]
Виклик:
істотно явно вказувати <code>pwsh</code>, якщо потрібен PowerShell 7.; REST API + PowerShell — популярна пара для інтеграцій і automation.; PowerShell використовують для:
PowerShell і Bash мають різну філософію.; Не варто запускати все від Administrator, якщо достатньо звичайного користувача.;<pre>
істотно: не всі errors за замовчуванням terminating.;<ref>https://learn.microsoft.com/en-us/powershell/</ref>
Приклади:
Приклад:
Logging
Приклад:
Для automation краще створювати окремі service accounts із мінімальними правами.; PowerShell особливо зручний у Windows і Azure environments.; # Використовувати-WhatIf для destructive operations.;
!; * Enter-PSSession — інтерактивна remote session.; Сильні сторони
[switch]$Force
Підходи:
PowerShell у Linux/macOS
Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending
Jobs
Azure PowerShell
Приклад сценарію:
Інтерактивна remote session:
Idempotent scripts безпечніші для deployment і configuration.;
Modules допомагають організувати scripts у reusable components.; * Pester — testing framework для PowerShell.;
Idempotency — властивість script, коли повторний запуск не ламає систему й не створює дублікати.; * Invoke-Command — cmdlet для виконання script block локально або віддалено.; Status -eq "Running"
{| class="wikitable"
Приклад:
Get-Greeting -Name "Anna"
[switch]$Force
<div style="background:#fff0f0;border-left:6px solid #eb5757;padding:14px 18px;margin:16px 0;border-radius:8px;">
Script Analyzer
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
[[Категорія:Безпека]] Добра практика — читати help перед запуском незнайомої команди.; * '''Hashtable''' — key-value структура.;<pre> Такі scripts корисні для адміністрування, але критичні операції мають бути захищені правами доступу й логуванням.;<pre> Поширені помилки: == Актуальна реліз == == Variables ==
Advanced functions підтримують common parameters, як ілюстрація:
./build.ps1
Сценарії: New-Item }
"Hello, $Name"
Remove-Item
[string]$UserName
Import-Module Az
Get-Process -Body $body `
Bash сильний для Unix scripting і текстових команд.;
ShouldProcess, щоб додати -WhatIf і -Confirm.;-Uri "https://api.example.com/items" `
- objects pipeline;
- cmdlets;
- modules;
- PowerShell Gallery;
- remoting;
- cross-platform PowerShell 7;
- Windows PowerShell 5.1 compatibility;
- JSON/CSV/XML;
- REST API;
- Azure і Microsoft 365;
- Pester;
- PSScriptAnalyzer;
- CI/CD;
- automation scripts;
- .NET integration.; Краще розуміти політику, підпис scripts і корпоративні правила.; New-ADUser
- отримати token;
- викликати endpoint;
- зберегти JSON;
- сформувати CSV-звіт;
- надіслати результат адміністратору.; Install-Module -Name Pester -Scope CurrentUser
Масив:
param( [string]$Path,
{{SEO