Powershell ADSIで指定OUのユーザー一覧取得

別ドメインのサーバから、Powershellを使って指定のActiveDirectory、OUのユーザー一覧を取得するスクリプトです。

# 資格情報取得
$Credential = Get-Credential

# オブジェクト作成
$Searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher

# 検索対象のADオブジェクトを定義
$Searcher.Filter = "(ObjectClass=user)"

# 検索対象のドメインを指定
$DomainDN = "LDAP://<AD SERVER NAME>.hogehoge.local/OU=<OUNAME>,DC=hogehoge,DC=local"

# 「DirectoryEntry」オブジェクトを作成し、ドメイン、資格情報を追加
$Domain = New-Object `
    -TypeName System.DirectoryServices.DirectoryEntry `
    -ArgumentList $DomainDN,
        $($Credential.UserName),
        $($Credential.GetNetworkCredential().password)

# 検索情報を追加
$Searcher.SearchRoot = $Domain

# 配列定義
$arg = @()

# 必要なプロパティのみ取得(任意に指定してください)
# ここでは「UserAccountControl」は16進数に変換している(末尾が 0x0002 はアカウントが無効)
# https://support.microsoft.com/ja-jp/help/305144/how-to-use-useraccountcontrol-to-manipulate-user-account-properties
foreach($list in $Searcher.FindAll()){
    $arg += $list.properties["name"][0] + "," + $list.properties["displayname"][0] + "," + $list.properties["useraccountcontrol"][0].Tostring("x")
} 

# CSVファイルに書き出し
$arg > AdUserList.csv

WordPress.com Blog.

ページ先頭へ ↑