PowerShellはWindows環境で使用される強力なスクリプト言語で、システム管理や自動化に広く使われています。以下に、PowerShellの基本構文とその例を紹介します。
# これはコメントです
$名前 = "ユーザー"
Get-Process # 実行中のプロセスを取得
Start-Service # サービスを開始
Stop-Service # サービスを停止
Get-Process | Sort-Object CPU -Descending # 実行中のプロセスをCPU使用率で降順に並べ替え
if ($値 -gt 10) {
Write-Output "値は10より大きいです"
} else {
Write-Output "値は10以下です"
}
# foreachループの例
$array = 1..5
foreach ($item in $array) {
Write-Output $item
}
# forループの例
for ($i = 0; $i -lt 5; $i++) {
Write-Output $i
}
function 挨拶 {
param ($名前)
Write-Output "こんにちは、$名前さん!"
}
# 関数の呼び出し
挨拶 -名前 "ユーザー"
=$variable = "value"
+, -, *, /, %$sum = 5 + 3
$product = 5 * 3
-eq, -ne, -gt, -lt, -ge, -leif ($a -eq $b) { "equal" }
if ($a -gt $b) { "greater" }
-and, -or, -notif ($a -eq 5 -and $b -eq 3) { "both conditions are true" }
,$array = 1, 2, 3, 4, 5
|Get-Process | Sort-Object -Property CPU
..$range = 1..10
$()$result = $(5 + 3) * 2
{}$scriptBlock = { param($x) $x * 2 }
## This is a comment
@echo off
powershell -NoProfile -ExecutionPolicy Bypass -File "YourScript.ps1"