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

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

PowerShellでユーザーアカウントを追加する

眠いので書き直すけど、ソースだけ一先ず。

書き直しました。先日は酷かった。。。
と、伴って命名仕方とかもちょっと工夫。こっちの方がしっくりくる。

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

function New-Account($context, $userName) {
    Write-Host $userName "アカウントを作成します..."
    $userPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context, [System.DirectoryServices.AccountManagement.IdentityType]::Name, $userName)
    
    # 作成する条件を満たしているかを検証
    if($userPrincipal -ne $null) {
        # 既に存在するアカウントなので処理を抜ける。
        Write-Host "既に存在するアカウント名です。"
        Write-Host $userName "アカウントを作成出来ませんでした..."
        return
    } else {
        # アカウントを作成
        $userPrincipal = New-Object System.DirectoryServices.AccountManagement.UserPrincipal($context);
        $userPrincipal.Name = $userName
        $userPrincipal.SamAccountName = $userName
        $userPrincipal.Enabled = $true;
        $userPrincipal.SetPassword($userName)
        $userPrincipal.PasswordNeverExpires = $true
        $userPrincipal.UnlockAccount()
        $userPrincipal.Save()

        Write-Host $userName "アカウントを作成しました..."
    }
    return $userPrincipal
}

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