💻

Active Directory:コンピューター情報をCSV出力

に公開
2026/03/13

オンプレAD環境で登録されているコンピューター情報の整理をするためにコンピューター名、説明、所属OUが欲しかったのでCSV出力するPowerShellを書いてみた。

前提条件

  • ドメインコントローラーにコンソールかリモートデスクトップでログオンして操作する
  • 管理者の PC から操作する場合は、Active Directory モジュールが使えること

処理の中身

  • コンピューター情報をCSV出力する
    • PC名
    • 所属OU
    • 説明
    • OSバージョン
    • IPv4Address(最終IP)
    • 最終ログオン日時

完成したスクリプト

GetAllPCName.ps1
<#
.SYNOPSIS
    指定OU配下のコンピュータ情報を抽出し、セキュリティ監査用の詳細情報を含めてCSV出力する。
#>
param (
    [Parameter(Mandatory=$false)]
    [string]$TargetOU = "OU=〇〇,DC=〇〇,DC=〇〇",

    [Parameter(Mandatory=$false)]
    [string]$OutFile = "PC_Inventory_List.csv"
)

$ErrorActionPreference = "Stop"

try {
    Write-Host "PCインベントリ抽出処理を開始します。対象OU: $TargetOU" -ForegroundColor Cyan

    if (-not (Get-Module -Name ActiveDirectory -ListAvailable)) {
        throw "ActiveDirectoryモジュールが存在しません。"
    }
    Import-Module ActiveDirectory

    # 【変更点】Propertiesに OS, IP, 最終ログオン日時 を追加
    $computers = Get-ADComputer -Filter * -SearchBase $TargetOU -SearchScope Subtree -Properties Description, OperatingSystem, IPv4Address, LastLogonDate

    if ($computers.Count -eq 0 -or $null -eq $computers) {
        Write-Warning "指定されたOU配下にコンピュータが存在しません。"
        exit
    }

    # パイプライン内でデータ加工・ソート・出力を完結
    $computers | Select-Object Name,
                               @{Name="ParentOU"; Expression={
                                   if ($_.DistinguishedName -match "OU=(.*?),") { $matches[1] } else { "None" }
                               }},
                               # 追加したプロパティを列として定義
                               Description,
                               #DistinguishedName,
                               OperatingSystem,
                               IPv4Address,
                               LastLogonDate |
                 Sort-Object -Property ParentOU, Name |
                 Export-Csv -Path $OutFile -Encoding UTF8 -NoTypeInformation -Force

    Write-Host "正常に完了しました。出力先: $($pwd)\$OutFile" -ForegroundColor Green

} catch {
    Write-Error "【エラー発生】処理中に問題が発生しました。`n詳細: $($_.Exception.Message)"
} finally {
    $ErrorActionPreference = "Continue"
}

Discussion