ひっそりと生きるプログラマのブログ

日頃気になった事なりを書き留めるブログです。関心ごとは多くもう少し更新頻度を上げたいところです。

PowerShellで任意のユーザーアカウントを取得する

前回は任意のグループ情報を取得しました。
今度は、任意のユーザー情報を取得します。

[void][reflection.assembly]::LoadWithPartialName("System.DirectoryServices")
[void][reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")

function Get-User($context, $userName) {
<#
    任意のコンテキストに含まれる任意のユーザーオブジェクトを返します。
    対象のオブジェクトを1件でも取得できた場合は、いずれかを返します。
    対象のオブジェクトの取得が 0 件の場合は、 null を返します。
    
    $context
        取得元となるコンテキスト
    $userName
        取得元となるユーザー名
#>
    $filter = New-Object System.DirectoryServices.AccountManagement.UserPrincipal($context)
    $filter.Name = $userName
    $searcher = New-Object System.DirectoryServices.AccountManagement.PrincipalSearcher($filter)
    $result = $searcher.FindOne()
    $searcher.Dispose()
    return $result
}

# テスト用コード
$context = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine)
Get-User $context "Guest"

以下のような結果が返ってきます。

GivenName                         : 
MiddleName                        : 
Surname                           : 
EmailAddress                      : 
VoiceTelephoneNumber              : 
EmployeeId                        : 
AdvancedSearchFilter              : System.DirectoryServices.AccountManagement.AdvancedFilters
Enabled                           : True
AccountLockoutTime                : 
LastLogon                         : 2015/10/08 0:45:03
PermittedWorkstations             : {}
PermittedLogonTimes               : {255, 255, 255, 255...}
AccountExpirationDate             : 
SmartcardLogonRequired            : False
DelegationPermitted               : True
BadLogonCount                     : 0
HomeDirectory                     : 
HomeDrive                         : 
ScriptPath                        : 
LastPasswordSet                   : 2015/10/08 14:17:33
LastBadPasswordAttempt            : 
PasswordNotRequired               : True
PasswordNeverExpires              : True
UserCannotChangePassword          : True
AllowReversiblePasswordEncryption : False
Certificates                      : {}
Context                           : System.DirectoryServices.AccountManagement.PrincipalContext
ContextType                       : Machine
Description                       : コンピューター/ドメインへのゲスト アクセス用 (ビルトイン アカウント)
DisplayName                       : 
SamAccountName                    : Guest
UserPrincipalName                 : 
Guid                              : 
DistinguishedName                 : 
StructuralObjectClass             : 
Name                              : Guest