PowerShellコマンド チートシート

ファイルシステム内のアイテムを管理するための基本的なコマンドレット。

アイテムの取得・存在確認

目的 コマンドレット
カレントディレクトリの取得 Get-Location (エイリアス: gl, pwd)
Get-Location
ディレクトリの内容表示 Get-ChildItem (エイリアス: gci, ls, dir)
# カレントディレクトリの内容
Get-ChildItem

# 特定のパスの内容 (-Path は省略可能)
Get-ChildItem -Path C:\Windows

# 再帰的に取得 (-Recurse)
Get-ChildItem -Path C:\Scripts -Recurse

# 特定の拡張子のみ (-Filter)
Get-ChildItem -Path C:\Logs -Filter *.log

# ファイルのみ表示 (-File) / ディレクトリのみ表示 (-Directory) (PSv3+)
Get-ChildItem -Path C:\Data -File
Get-ChildItem -Path C:\Data -Directory

# 非表示ファイル・隠しファイルも含める (-Force)
Get-ChildItem -Path C:\Users\Public -Force
アイテムの存在確認 Test-Path
# ファイルの存在確認
Test-Path -Path C:\path\to\file.txt

# ディレクトリの存在確認
Test-Path -Path C:\path\to\directory

# パスがコンテナ(ディレクトリ)か確認 (-PathType Container)
Test-Path -Path C:\Windows -PathType Container

# パスがリーフ(ファイル)か確認 (-PathType Leaf)
Test-Path -Path C:\Windows\System32\notepad.exe -PathType Leaf
ファイルのコンテンツ取得 Get-Content (エイリアス: gc, cat, type)
# ファイル全体を読み込む
Get-Content -Path C:\logs\app.log

# 先頭から指定した行数を読み込む (-TotalCount)
Get-Content -Path C:\logs\app.log -TotalCount 10

# 末尾から指定した行数を読み込む (-Tail)
Get-Content -Path C:\logs\app.log -Tail 5

# リアルタイムで追記を監視 (-Wait)
Get-Content -Path C:\logs\app.log -Wait

# バイト配列として読み込む (-AsByteStream)
Get-Content -Path C:\images\logo.png -AsByteStream

# 生の文字列として読み込む (-Raw)
Get-Content -Path C:\config.json -Raw

アイテムの作成・変更・移動・削除

目的 コマンドレット
ディレクトリの変更 Set-Location (エイリアス: sl, cd, chdir)
# 指定したディレクトリに移動
Set-Location -Path C:\Windows

# 親ディレクトリに移動
Set-Location ..

# ドライブのルートに移動
Set-Location \

# 特定のドライブに移動
Set-Location C:
Set-Location D:
新しいアイテム(ファイル/ディレクトリ)の作成 New-Item (エイリアス: ni)
# 新しいディレクトリを作成 (-ItemType Directory)
New-Item -Path C:\Temp\NewFolder -ItemType Directory

# 新しい空ファイルを作成 (-ItemType File)
New-Item -Path C:\Temp\NewFile.txt -ItemType File

# 中間ディレクトリも同時に作成 (-Force)
New-Item -Path C:\Temp\subdir1\subdir2\NewFile.txt -ItemType File -Force
アイテムのコピー Copy-Item (エイリアス: cpi, cp, copy)
# ファイルをコピー
Copy-Item -Path C:\source\file.txt -Destination C:\destination\

# ファイル名を変更してコピー
Copy-Item -Path C:\source\file.txt -Destination C:\destination\new_file.txt

# ディレクトリを再帰的にコピー (-Recurse)
Copy-Item -Path C:\source\folder -Destination C:\destination\ -Recurse

# 確認プロンプトを表示しない (-Force) ※上書き時など
Copy-Item -Path C:\source\file.txt -Destination C:\destination\ -Force
アイテムの移動 Move-Item (エイリアス: mi, mv, move)
# ファイルを移動
Move-Item -Path C:\source\file.txt -Destination C:\destination\

# ファイル名を変更して移動
Move-Item -Path C:\source\file.txt -Destination C:\destination\moved_file.txt

# ディレクトリを移動
Move-Item -Path C:\source\folder -Destination C:\destination\

# 確認プロンプトを表示しない (-Force) ※上書き時など
Move-Item -Path C:\source\file.txt -Destination C:\destination\ -Force
アイテム名の変更 Rename-Item (エイリアス: rni, ren)
# ファイル名を変更
Rename-Item -Path C:\path\to\old_name.txt -NewName new_name.txt

# ディレクトリ名を変更
Rename-Item -Path C:\path\to\old_folder -NewName new_folder

# 確認プロンプトを表示しない (-Force)
Rename-Item -Path C:\path\to\item.log -NewName item.bak -Force
アイテムの削除 Remove-Item (エイリアス: ri, rm, del, erase, rd)
# ファイルを削除
Remove-Item -Path C:\path\to\file_to_delete.txt

# ディレクトリを削除(空の場合のみ)
Remove-Item -Path C:\path\to\empty_folder

# ディレクトリを中身ごと削除 (-Recurse)
Remove-Item -Path C:\path\to\folder_to_delete -Recurse

# 確認プロンプトを表示しない (-Force)
Remove-Item -Path C:\path\to\dangerous_file.exe -Force

# 読み取り専用ファイルも強制削除 (-Force)
Remove-Item -Path C:\path\to\readonly.txt -Force
ファイルへのコンテンツ書き込み/追記 Set-Content (エイリアス: sc) / Add-Content (エイリアス: ac)
# ファイルに上書き (-Value で内容を指定)
Set-Content -Path C:\output.txt -Value "This is the new content."

# パイプラインから受け取った内容で上書き
Get-Process | Out-String | Set-Content -Path C:\processes.txt

# ファイルに追記 (-Value で内容を指定)
Add-Content -Path C:\log.txt -Value "Log entry at $(Get-Date)"

# パイプラインから受け取った内容を追記
"Another line" | Add-Content -Path C:\log.txt
ファイルのコンテンツ置換 (Get-Content ...) -replace ... | Set-Content ...
# ファイル内の 'old_text' を 'new_text' に置換して上書き
(Get-Content C:\config.ini) -replace 'old_text', 'new_text' | Set-Content C:\config.ini

# 正規表現を使用した置換
(Get-Content C:\data.csv) -replace '\d{4}-\d{2}-\d{2}', (Get-Date -Format 'yyyy/MM/dd') | Set-Content C:\data_new.csv

OS、ハードウェア、環境変数などのシステム情報を取得します。

目的 コマンドレット / 変数
OS情報取得 (WMI/CIM) Get-CimInstance (推奨) / Get-WmiObject (旧)
# OS情報の取得 (Win32_OperatingSystem クラス)
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object Caption, Version, OSArchitecture, InstallDate

# コンピュータシステムの基本情報 (Win32_ComputerSystem クラス)
Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object Manufacturer, Model, TotalPhysicalMemory

# BIOS情報 (Win32_BIOS クラス)
Get-CimInstance -ClassName Win32_BIOS | Select-Object Manufacturer, Version, SerialNumber
環境変数の取得 $env: / Get-ChildItem Env:
# 特定の環境変数を表示 (例: PATH)
$env:PATH

# 環境変数の一覧を表示
Get-ChildItem Env:

# 環境変数名でフィルタリング
Get-ChildItem Env: | Where-Object Name -like '*USER*'
日付・時刻の取得 Get-Date
# 現在の日付と時刻
Get-Date

# 指定した書式で表示 (-Format)
Get-Date -Format "yyyy/MM/dd HH:mm:ss"
Get-Date -Format g  # 一般的な短い形式
Get-Date -Format G  # 一般的な長い形式

# UFormat (Unix形式) で表示 (-UFormat)
Get-Date -UFormat %Y-%m-%d_%H-%M-%S
PowerShellのバージョン確認 $PSVersionTable
# PowerShell バージョンテーブル全体を表示
$PSVersionTable

# 特定のプロパティを表示 (例: PSVersion)
$PSVersionTable.PSVersion

# PowerShell Edition (Desktop / Core) を表示
$PSVersionTable.PSEdition
コンピュータ名の取得 $env:COMPUTERNAME / hostname
# 環境変数から取得
$env:COMPUTERNAME

# hostnameコマンド (外部コマンド)
hostname
ホットフィックス(更新プログラム)の取得 Get-HotFix
# インストールされているHotFixを一覧表示
Get-HotFix

# 特定のHotFix IDで検索 (-Id)
Get-HotFix -Id KB5001330

# 特定の説明で検索 (-Description)
Get-HotFix -Description "Security Update"

# 特定のコンピュータに対して実行 (-ComputerName)
Get-HotFix -ComputerName SERVER01, SERVER02

実行中のプロセスを管理します。

目的 コマンドレット
プロセスの一覧取得 Get-Process (エイリアス: gps, ps)
# すべてのプロセスを取得
Get-Process

# 特定の名前のプロセスを取得 (-Name)
Get-Process -Name notepad, chrome

# プロセスIDで取得 (-Id)
Get-Process -Id 1234, 5678

# 特定のプロパティを表示 (Select-Object)
Get-Process | Select-Object Name, Id, CPU, WorkingSet

# CPU使用率が高い順にソート
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10
プロセスの停止 Stop-Process (エイリアス: spps, kill)
# 名前でプロセスを停止 (-Name)
Stop-Process -Name notepad

# プロセスIDで停止 (-Id)
Stop-Process -Id 1234

# Get-Processからパイプラインで渡して停止
Get-Process -Name "calc" | Stop-Process

# 確認プロンプトを表示しない (-Force)
Stop-Process -Name "hungapp" -Force

# 停止前に確認する (-Confirm)
Stop-Process -Name "important_process" -Confirm
新しいプロセスの開始 Start-Process (エイリアス: saps, start)
# アプリケーションを起動 (-FilePath)
Start-Process -FilePath "notepad.exe"

# 引数を指定して起動 (-ArgumentList)
Start-Process -FilePath "C:\Program Files\MyApp\app.exe" -ArgumentList "-config C:\config.xml", "-silent"

# 管理者権限で起動 (-Verb RunAs)
Start-Process -FilePath "cmd.exe" -Verb RunAs

# ドキュメントを指定したアプリケーションで開く
Start-Process -FilePath "C:\docs\document.docx"

# URLを既定のブラウザで開く
Start-Process "https://learn.microsoft.com/powershell/"
プロセスの待機 Wait-Process
# 指定したプロセスが終了するまで待機 (-Name)
Wait-Process -Name notepad

# 指定したプロセスIDが終了するまで待機 (-Id)
Wait-Process -Id 1234

# タイムアウト付きで待機 (-Timeout 秒数)
Wait-Process -Name "background_task" -Timeout 300 # 5分待機

# Start-Processで起動したプロセスの終了を待つ (-Wait)
Start-Process notepad -Wait

Windows サービスの状態を確認したり、操作したりします。

目的 コマンドレット
サービスの一覧取得 Get-Service (エイリアス: gsv)
# すべてのサービスを取得
Get-Service

# 特定の名前のサービスを取得 (-Name) ワイルドカード使用可
Get-Service -Name spooler, wuauserv
Get-Service -Name BITS*

# 表示名でサービスを取得 (-DisplayName) ワイルドカード使用可
Get-Service -DisplayName "Windows Update", "*Print*"

# 依存しているサービスを取得 (-DependentServices)
Get-Service -Name RpcSs -DependentServices

# 依存先のサービスを取得 (-RequiredServices / -ServicesDependedOn)
Get-Service -Name LanmanWorkstation -RequiredServices

# 特定のコンピュータのサービスを取得 (-ComputerName)
Get-Service -ComputerName SERVER01
サービスの開始 Start-Service (エイリアス: sasv)
# 名前でサービスを開始 (-Name)
Start-Service -Name spooler

# 表示名でサービスを開始 (-DisplayName)
Start-Service -DisplayName "Print Spooler"

# Get-Serviceからパイプラインで渡して開始
Get-Service -Name BITS | Start-Service
サービスの停止 Stop-Service (エイリアス: spsv)
# 名前でサービスを停止 (-Name)
Stop-Service -Name spooler

# 表示名でサービスを停止 (-DisplayName)
Stop-Service -DisplayName "Print Spooler"

# Get-Serviceからパイプラインで渡して停止
Get-Service -Name WSearch | Stop-Service

# 依存サービスも一緒に停止 (-Force) ※注意して使用
Stop-Service -Name http -Force

# 停止できない場合にエラーを発生させない (-NoWait と併用する場合など)
Stop-Service -Name SomeService -ErrorAction SilentlyContinue
サービスの再起動 Restart-Service (エイリアス: rs)
# 名前でサービスを再起動 (-Name)
Restart-Service -Name spooler

# 表示名でサービスを再起動 (-DisplayName)
Restart-Service -DisplayName "Print Spooler"

# Get-Serviceからパイプラインで渡して再起動
Get-Service -Name Dnscache | Restart-Service

# 依存サービスも一緒に再起動 (-Force) ※注意して使用
Restart-Service -Name Netlogon -Force
サービスのプロパティ変更 Set-Service
# スタートアップの種類を変更 (-StartupType) (Automatic, Manual, Disabled)
Set-Service -Name BITS -StartupType Manual

# 説明を変更 (-Description)
Set-Service -Name MyCustomService -Description "My custom background service."

# 表示名を変更 (-DisplayName)
Set-Service -Name AppIDSvc -DisplayName "Application Identity Service Custom Name"

# Get-Serviceからパイプラインで渡して変更
Get-Service -Name wuauserv | Set-Service -StartupType Disabled
新しいサービスの作成 New-Service
# 新しいサービスを作成
New-Service -Name "MyNewSvc" -BinaryPathName "C:\Services\MyService.exe" `
    -DisplayName "My New Service" -Description "This is a test service." `
    -StartupType Automatic

ネットワーク設定の確認やテスト、通信を行います。

目的 コマンドレット
IP構成の表示 Get-NetIPConfiguration (推奨) / ipconfig (外部)
# すべてのネットワークアダプタのIP構成を表示
Get-NetIPConfiguration

# 詳細情報を表示 (-Detailed)
Get-NetIPConfiguration -Detailed

# 特定のアダプタインターフェイスインデックスを指定
Get-NetIPConfiguration -InterfaceIndex 12

# ipconfig コマンド (外部コマンド)
ipconfig /all
IPアドレス情報の表示 Get-NetIPAddress
# すべてのIPアドレス情報を表示
Get-NetIPAddress

# IPv4アドレスのみ表示 (-AddressFamily IPv4)
Get-NetIPAddress -AddressFamily IPv4

# 特定のインターフェイスのIPアドレスを表示
Get-NetIPAddress -InterfaceAlias "Ethernet"

# 有効なIPアドレスのみ表示
Get-NetIPAddress | Where-Object {$_.AddressState -eq 'Preferred'}
ネットワーク接続テスト (Ping) Test-Connection (エイリアス: ping ※内部)
# 指定したホストにPing送信
Test-Connection -ComputerName www.google.com

# 送信回数を指定 (-Count)
Test-Connection -ComputerName 192.168.1.1 -Count 10

# 詳細情報を表示 (-InformationLevel Detailed)
Test-Connection -ComputerName localhost -InformationLevel Detailed

# 複数のホストにPing送信
Test-Connection -ComputerName "server1", "server2", "8.8.8.8"

# 結果をシンプルに表示 (-Quiet) ※True/Falseを返す
Test-Connection -ComputerName "nonexistent-host" -Quiet -ErrorAction SilentlyContinue
ポート接続テスト Test-NetConnection (エイリアス: tnc)
# 指定したホストの特定のポートに接続テスト (-Port)
Test-NetConnection -ComputerName www.google.com -Port 443

# Pingテストのみ実行
Test-NetConnection -ComputerName 192.168.1.1 -InformationLevel "Quiet"

# ルートトレースを実行 (-TraceRoute)
Test-NetConnection -ComputerName www.bing.com -TraceRoute

# 詳細な診断情報 (-Diagnose) ※時間がかかる場合あり
# Test-NetConnection -Diagnose
Webコンテンツの取得 Invoke-WebRequest (エイリアス: iwr, wget, curl)
# Webページのコンテンツを取得 (-Uri)
Invoke-WebRequest -Uri "https://www.example.com"

# 結果をファイルに保存 (-OutFile)
Invoke-WebRequest -Uri "https://domain.com/file.zip" -OutFile "C:\downloads\file.zip"

# HTTPメソッドを指定 (-Method) (GET, POST, PUT, DELETE など)
Invoke-WebRequest -Uri "https://api.example.com/data" -Method POST -Body $jsonData -ContentType "application/json"

# ヘッダーを指定 (-Headers)
$headers = @{ "Authorization" = "Bearer YOUR_TOKEN" }
Invoke-WebRequest -Uri "https://api.example.com/resource" -Headers $headers

# Basic認証を使用 (-Credential)
$cred = Get-Credential
Invoke-WebRequest -Uri "https://secure.example.com" -Credential $cred

# 生のコンテンツのみ取得 (-UseBasicParsing は非推奨気味、状況による)
# Invoke-RestMethod の方が適している場合が多い
(Invoke-WebRequest -Uri "https://ifconfig.me/ip").Content
REST APIの呼び出し Invoke-RestMethod (エイリアス: irm)
# REST API (GET) を呼び出し、結果をPowerShellオブジェクトとして取得
Invoke-RestMethod -Uri "https://api.github.com/users/powershell"

# JSONデータをPOSTで送信
$body = @{ key = "value"; id = 123 } | ConvertTo-Json
Invoke-RestMethod -Uri "https://httpbin.org/post" -Method Post -Body $body -ContentType "application/json"

# 結果をファイルに保存 (-OutFile)
Invoke-RestMethod -Uri "https://api.example.com/getfile" -OutFile "C:\output\data.json"

# ヘッダーや認証は Invoke-WebRequest と同様に指定可能
$headers = @{ "X-Api-Key" = "YOUR_API_KEY" }
Invoke-RestMethod -Uri "https://api.custom.com/v1/items" -Headers $headers

変数への代入、配列やハッシュテーブルの操作、オブジェクトの選択・変換など。

基本的な操作

目的 構文 / コマンドレット
変数への代入 $variableName = value
# 文字列
$message = "Hello, PowerShell!"
# 数値
$count = 10
# コマンドの結果
$processes = Get-Process
# 配列
$array = 1, 2, "three", $false
# ハッシュテーブル
$hashtable = @{ Name = "Alice"; Age = 30; City = "Tokyo" }
配列の操作 インデックス[], +=, +
$myArray = "apple", "banana", "cherry"
# 要素へのアクセス (0から始まるインデックス)
$myArray[0] # "apple"
$myArray[-1] # "cherry" (末尾)
# 要素の追加 (新しい配列が作成される)
$myArray += "orange"
# 配列の結合 (新しい配列が作成される)
$newArray = $myArray + @("grape", "melon")
# 要素数
$myArray.Count
ハッシュテーブルの操作 キー. or [], +=, .Add(), .Remove()
$myHash = @{ ID = 101; Name = "Bob"; Status = "Active" }
# 値へのアクセス
$myHash.Name # "Bob"
$myHash["Status"] # "Active"
# 要素の追加/更新
$myHash.Department = "Sales"
$myHash["Status"] = "Inactive"
$myHash.Add("Location", "Osaka") # キーが存在するとエラー
# 要素の削除
$myHash.Remove("Status")
# キーの一覧
$myHash.Keys
# 値の一覧
$myHash.Values

オブジェクトの操作とフィルタリング

目的 コマンドレット
オブジェクトのプロパティ選択 Select-Object (エイリアス: select)
# 指定したプロパティのみ選択
Get-Process | Select-Object -Property Name, Id, CPU

# 最初のN個のオブジェクトを選択 (-First)
Get-ChildItem | Select-Object -First 5

# 最後のN個のオブジェクトを選択 (-Last)
Get-EventLog -LogName System -Newest 100 | Select-Object -Last 10

# 指定したプロパティを除外 (-ExcludeProperty)
Get-Service | Select-Object -ExcludeProperty DependentServices, ServicesDependedOn

# 計算されたプロパティを追加 (ハッシュテーブルで定義)
Get-Process | Select-Object Name, Id, @{Name='VM_MB';Expression={$_.VM / 1MB -as [int]}}

# オブジェクトを展開 (-ExpandProperty) ※配列などのプロパティを展開
(Get-CimInstance Win32_ComputerSystem).PartOfDomain | Select-Object -ExpandProperty Name
オブジェクトのフィルタリング Where-Object (エイリアス: where, ?)
# 条件に一致するオブジェクトをフィルタリング (クラシック構文)
Get-Service | Where-Object {$_.Status -eq 'Running'}

# 条件に一致するオブジェクトをフィルタリング (シンプル構文 PSv3+)
Get-Process | Where-Object Name -like 's*' # sで始まるプロセス
Get-ChildItem C:\Windows | Where-Object Length -gt 10MB # 10MBより大きいファイル
Get-EventLog System | Where-Object EventID -in 1001, 1002 # EventIDが1001または1002

# 複数の条件 (AND)
Get-Process | Where-Object {$_.CPU -gt 100 -and $_.WorkingSet -gt 500MB}
# 複数の条件 (OR)
Get-Service | Where-Object {$_.Status -eq 'Stopped' -or $_.StartType -eq 'Disabled'}
オブジェクトのソート Sort-Object (エイリアス: sort)
# 指定したプロパティで昇順ソート
Get-Process | Sort-Object -Property Name

# 指定したプロパティで降順ソート (-Descending)
Get-ChildItem | Sort-Object -Property Length -Descending

# 複数のプロパティでソート
Get-Service | Sort-Object -Property Status, Name

# 重複を除外 (-Unique) ※ソート後に適用される
@(1, 3, 2, 3, 1, 4) | Sort-Object -Unique
オブジェクトのグループ化 Group-Object (エイリアス: group)
# ステータスごとにサービスをグループ化
Get-Service | Group-Object -Property Status

# 拡張子ごとにファイルをグループ化
Get-ChildItem | Group-Object -Property Extension

# グループ化結果からカウントと名前のみ表示
Get-Process | Group-Object -Property Company | Select-Object Count, Name

# グループ化されたアイテム自体は Group プロパティにある
Get-ChildItem *.log | Group-Object {$_.LastWriteTime.Date} | Sort-Object Name
オブジェクトの測定 (数値計算) Measure-Object (エイリアス: measure)
# ファイルサイズの合計、平均、最大、最小を計算
Get-ChildItem C:\Windows\*.log | Measure-Object -Property Length -Sum -Average -Maximum -Minimum

# 行数、単語数、文字数をカウント (-Line, -Word, -Character)
Get-Content C:\log.txt | Measure-Object -Line -Word -Character

# オブジェクトの数をカウント (プロパティ指定なし)
Get-Process | Measure-Object # Count プロパティ
コレクションの各要素に対する処理 ForEach-Object (エイリアス: foreach, %)
# 各プロセスの名前とIDを表示 (クラシック構文)
Get-Process | ForEach-Object { Write-Host "Name: $($_.Name), ID: $($_.Id)" }

# 各サービスの表示名を大文字に変換 (シンプル構文 PSv3+)
Get-Service | ForEach-Object DisplayName -Upper

# 各ファイル名にプレフィックスを追加してリネーム
Get-ChildItem *.txt | ForEach-Object { Rename-Item -Path $_.FullName -NewName "prefix_$($_.Name)" }

# Begin, Process, End ブロックの使用
1..3 | ForEach-Object -Begin { $total = 0 } -Process { $total += $_ } -End { "Total: $total" }

データ形式の変換

目的 コマンドレット
CSV形式への変換/エクスポート ConvertTo-Csv / Export-Csv
# オブジェクトをCSV形式の文字列に変換
Get-Process | Select-Object Name, Id, CPU | ConvertTo-Csv -NoTypeInformation

# オブジェクトをCSVファイルにエクスポート (-Path)
Get-Service | Export-Csv -Path C:\services.csv -NoTypeInformation -Encoding UTF8

# 区切り文字を指定 (-Delimiter)
Get-Process | Export-Csv -Path C:\processes.tsv -Delimiter "`t" -NoTypeInformation

# 既存ファイルに追記 (-Append)
Get-Process -Name chrome | Export-Csv -Path C:\chrome_processes.csv -Append -NoTypeInformation
CSV形式からのインポート Import-Csv
# CSVファイルをインポートしてオブジェクトの配列にする
$data = Import-Csv -Path C:\users.csv

# ヘッダーを指定 (-Header) ※CSVにヘッダー行がない場合
Import-Csv -Path C:\data_noheader.csv -Header "Col1", "Col2", "Col3"

# 区切り文字を指定 (-Delimiter)
Import-Csv -Path C:\data.tsv -Delimiter "`t"

# インポートしたデータを使用
Import-Csv -Path C:\servers.csv | ForEach-Object { Test-Connection -ComputerName $_.ServerName -Count 1 }
JSON形式への変換 ConvertTo-Json
# オブジェクトをJSON形式の文字列に変換
Get-Process | Select-Object Name, Id | ConvertTo-Json

# ハッシュテーブルをJSONに変換
@{ Name = "David"; Age = 25 } | ConvertTo-Json

# 階層の深さを指定 (-Depth)
Get-ChildItem | Select-Object Name, Length, LastWriteTime | ConvertTo-Json -Depth 3

# コンパクトな形式 (-Compress)
Get-Service | Select-Object Name, Status | ConvertTo-Json -Compress
JSON形式からの変換 ConvertFrom-Json
# JSON文字列をPowerShellオブジェクト (PSCustomObject / Hashtable) に変換
$jsonString = '{"name":"Eve", "city":"London"}'
$obj = $jsonString | ConvertFrom-Json
$obj.name # Eve

# REST APIの結果 (JSON) をオブジェクトに変換して使用
$apiResult = Invoke-RestMethod -Uri "https://api.example.com/data"
$apiResult | ConvertFrom-Json | ForEach-Object { Write-Host $_.item_id }
XML形式への変換/エクスポート ConvertTo-Xml / Export-Clixml
# オブジェクトをXML形式 (Clixml) にエクスポート (PowerShellでの再利用に最適)
Get-Process | Export-Clixml -Path C:\processes.xml

# オブジェクトを汎用的なXML Documentに変換 (限定的)
# Get-Date | ConvertTo-Xml -As Document
XML形式からのインポート Import-Clixml / [xml] キャスト
# Export-Clixmlで保存したファイルをインポートしてオブジェクトを復元
$processes = Import-Clixml -Path C:\processes.xml

# 汎用的なXMLファイルを読み込む
[xml]$xmlDoc = Get-Content C:\config.xml
$xmlDoc.configuration.appSettings.add | Where-Object {$_.key -eq 'ConnectionString'}

スクリプトの流れを制御するための構文(条件分岐、繰り返しなど)。

目的 構文
条件分岐 (If-ElseIf-Else) if (condition) { ... } elseif (condition) { ... } else { ... }
$num = Get-Random -Minimum 1 -Maximum 10
if ($num -lt 5) {
    Write-Host "$num is less than 5."
}
elseif ($num -eq 5) {
    Write-Host "$num is exactly 5."
}
else {
    Write-Host "$num is greater than 5."
}
条件分岐 (Switch) switch (value) { condition { ... } condition { ... } default { ... } }
$day = (Get-Date).DayOfWeek
switch ($day) {
    'Monday' { Write-Host "Start of the week." }
    'Friday' { Write-Host "Almost weekend!" }
    'Saturday' { Write-Host "Weekend! 🎉" }
    'Sunday' { Write-Host "Weekend! 🎉" }
    default { Write-Host "It's a weekday." }
}

# ワイルドカードや正規表現も使用可能 (-Wildcard, -Regex)
$fileName = "Report_2024_Final.docx"
switch -Wildcard ($fileName) {
    '*.txt' { Write-Host "Text file" }
    'Report*.docx' { Write-Host "Word Report file" }
    default { Write-Host "Other file type" }
}
繰り返し (For) for (initialization; condition; increment) { ... }
for ($i = 1; $i -le 5; $i++) {
    Write-Host "Iteration number $i"
}
繰り返し (ForEach) ※コレクション用 foreach ($item in $collection) { ... }
$colors = "Red", "Green", "Blue"
foreach ($color in $colors) {
    Write-Host "Current color: $color"
}
注意: パイプラインで使用する ForEach-Object (エイリアス foreach, %) とは異なります。
繰り返し (While) while (condition) { ... }
$count = 0
while ($count -lt 3) {
    Write-Host "Count is $count"
    $count++
}
繰り返し (Do-While/Do-Until) do { ... } while (condition)
do { ... } until (condition)
# Do-While (最低1回実行し、条件がTrueの間繰り返す)
$x = 5
do {
    Write-Host "x = $x"
    $x--
} while ($x -gt 0)

# Do-Until (最低1回実行し、条件がTrueになるまで繰り返す)
$y = 0
do {
    Write-Host "y = $y"
    $y++
} until ($y -ge 3)
ループの制御 (Break/Continue) break / continue
# Break: ループを抜ける
foreach ($i in 1..10) {
    if ($i -eq 5) {
        Write-Host "Breaking at 5"
        break
    }
    Write-Host $i
}

# Continue: 現在のイテレーションをスキップして次に進む
foreach ($i in 1..5) {
    if ($i -eq 3) {
        Write-Host "Skipping 3"
        continue
    }
    Write-Host $i
}

日常的なタスクやスクリプト作成に役立つその他のコマンドレット。

目的 コマンドレット
コンソールへの出力 Write-Host, Write-Output, Write-Verbose, Write-Warning, Write-Error
# ホスト (コンソール) に直接出力 (パイプライン非推奨)
Write-Host "This message goes directly to the console." -ForegroundColor Yellow

# パイプラインに出力 (推奨)
Write-Output "This message can be passed through the pipeline."
"This implicit output also goes to the pipeline." | Get-Member # パイプラインに渡る

# 詳細メッセージ (実行には $VerbosePreference = 'Continue' が必要)
Write-Verbose "This is a verbose message."

# 警告メッセージ
Write-Warning "This is a warning message."

# エラーメッセージ (スクリプトは停止しない)
Write-Error "This is a non-terminating error." -Message "Something went wrong but continuing."
コマンドのヘルプ表示 Get-Help (エイリアス: help, man)
# コマンドレットの基本ヘルプ
Get-Help Get-Process

# 詳細なヘルプ (-Detailed)
Get-Help Get-Service -Detailed

# 完全なヘルプ (-Full)
Get-Help Copy-Item -Full

# パラメータごとの詳細 (-Parameter)
Get-Help Move-Item -Parameter Path

# 使用例のみ表示 (-Examples)
Get-Help Select-Object -Examples

# オンラインで最新ヘルプを開く (-Online)
Get-Help Invoke-WebRequest -Online

# ヘルプコンテンツの更新 (管理者権限が必要)
# Update-Help
コマンドの検索 Get-Command (エイリアス: gcm)
# 名前に "Process" を含むコマンドを検索 (-Name)
Get-Command -Name *Process*

# "Service" を操作するコマンド (動詞がSet) を検索 (-Verb)
Get-Command -Verb Set -Noun *Service*

# 特定のモジュール内のコマンドを検索 (-Module)
Get-Command -Module NetTCPIP

# コマンドの種類を指定 (-CommandType) (Cmdlet, Function, Alias, Application)
Get-Command -CommandType Alias -Name ls, dir, cat

# パラメータ名でコマンドを検索 (-ParameterName)
Get-Command -ParameterName ComputerName
オブジェクトのメンバー (プロパティ/メソッド) 表示 Get-Member (エイリアス: gm)
# オブジェクトのメンバーを表示
Get-Process | Get-Member

# 特定の種類のメンバーのみ表示 (-MemberType) (Property, Method, Event, etc.)
Get-Service | Get-Member -MemberType Property

# 静的メンバーを表示 (-Static) ※クラス自体に対して使用
[System.DateTime] | Get-Member -Static

# 変数に入れたオブジェクトのメンバーを表示
$myString = "hello"
$myString | Get-Member
スクリプトの実行ポリシー管理 Get-ExecutionPolicy / Set-ExecutionPolicy
# 現在の実行ポリシーを表示
Get-ExecutionPolicy

# 有効なポリシーの一覧を表示 (-List)
Get-ExecutionPolicy -List

# 実行ポリシーを変更 (管理者権限が必要) (-ExecutionPolicy)
# Restricted, AllSigned, RemoteSigned, Unrestricted, Bypass, Undefined
# Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
セキュリティ設定のため、Set-ExecutionPolicy の使用は慎重に行ってください。
モジュールの管理 Get-Module, Import-Module, Remove-Module, Install-Module, Update-Module, Find-Module
# 現在のセッションにインポートされているモジュールを表示
Get-Module

# 利用可能なモジュールを表示 (-ListAvailable)
Get-Module -ListAvailable

# モジュールをインポート
Import-Module ActiveDirectory
Import-Module C:\Path\To\MyModule.psd1 -Force # 再インポート

# モジュールを削除
Remove-Module ActiveDirectory

# PowerShell Gallery からモジュールを検索
Find-Module -Name *Azure*

# モジュールをインストール (管理者権限推奨)
# Install-Module -Name Az -Scope CurrentUser -AllowClobber -Force

# インストール済みモジュールを更新
# Update-Module -Name Az
一時停止 Start-Sleep (エイリアス: sleep)
# 指定した秒数だけ停止 (-Seconds)
Write-Host "Waiting for 5 seconds..."
Start-Sleep -Seconds 5
Write-Host "Done."

# ミリ秒で停止 (-Milliseconds)
Start-Sleep -Milliseconds 500
乱数の生成 Get-Random
# 0 から Int32.MaxValue までのランダムな整数
Get-Random

# 最小値と最大値を指定 (-Minimum, -Maximum) ※Maximumは含まない
Get-Random -Minimum 1 -Maximum 101 # 1 から 100 までの整数

# 配列からランダムに要素を選択
$items = "A", "B", "C", "D", "E"
Get-Random -InputObject $items

# 配列から複数ランダムに選択 (-Count)
Get-Random -InputObject $items -Count 3

Windows レジストリのキーや値を操作します。PowerShell Drive (PSDrive) としてアクセスします (例: HKLM:, HKCU:)。

レジストリの変更はシステムに影響を与える可能性があるため、慎重に行ってください。バックアップを推奨します。
目的 コマンドレット / 操作
レジストリキーの内容表示 Get-ChildItem (エイリアス: gci, ls, dir)
# HKEY_CURRENT_USER\Software のサブキーを表示
Get-ChildItem HKCU:\Software

# HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services のサブキーを表示
dir HKLM:\System\CurrentControlSet\Services
レジストリキーの値を取得 Get-ItemProperty (エイリアス: gp)
# 特定のキーにあるすべての値を取得
Get-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer

# 特定の値を取得 (-Name)
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName

# (既定) の値を取得 (値の名前が空文字列 or null)
(Get-ItemProperty -Path HKCR:\.txt).'(default)'
新しいレジストリキーを作成 New-Item (エイリアス: ni)
# 新しいキーを作成
New-Item -Path HKCU:\Software\MyNewAppKey

# 中間キーも同時に作成 (-Force)
New-Item -Path "HKLM:\SOFTWARE\MyCompany\MyApp\Settings" -Force
レジストリ値の作成/設定 New-ItemProperty / Set-ItemProperty
# 新しい値を作成 (文字列: String)
New-ItemProperty -Path HKCU:\Software\MyNewAppKey -Name "Version" -Value "1.0" -PropertyType String

# 新しい値を作成 (DWORD 32ビット: DWord)
New-ItemProperty -Path HKCU:\Software\MyNewAppKey -Name "IsEnabled" -Value 1 -PropertyType DWord

# 既存の値を変更 (Set-ItemProperty)
Set-ItemProperty -Path HKCU:\Software\MyNewAppKey -Name "Version" -Value "1.1"

# 値が存在しない場合は Set-ItemProperty でも作成される
Set-ItemProperty -Path HKCU:\Software\MyNewAppKey -Name "LastCheck" -Value (Get-Date)
レジストリキー/値の存在確認 Test-Path
# キーの存在確認
Test-Path HKCU:\Software\MyNewAppKey

# 値の存在確認 (キーパス + '\' + 値の名前) ※少し技巧的
# Test-Path 'HKCU:\Software\MyNewAppKey\Version' # これは機能しない場合が多い
# (Get-ItemProperty HKCU:\Software\MyNewAppKey).PSObject.Properties.Name -contains 'Version' # より確実
レジストリキーの削除 Remove-Item (エイリアス: ri, del)
# レジストリキーを削除 (サブキーや値がない場合)
Remove-Item -Path HKCU:\Software\MyNewAppKeyToDelete

# レジストリキーを再帰的に削除 (サブキーや値があっても削除) (-Recurse)
Remove-Item -Path HKCU:\Software\MyOldAppKey -Recurse -Force
レジストリ値の削除 Remove-ItemProperty
# 特定の値を削除 (-Name)
Remove-ItemProperty -Path HKCU:\Software\MyNewAppKey -Name "ObsoleteValue" -Force