[Windows/PowerShell] PowerShell を使用して複数のリモートコンピューターにアカウントを作りたい.
技術ノート
2016/11/02
[番号]
技術ノート KGTN 2016101903
[現象]
[Windows/PowerShell] PowerShell を使用して複数のリモートコンピューターにアカウントを作りたい.
[説明]
以下に,各リモートコンピューターにアカウントを作成するサンプルを示します.
$hostList = @("192.168.102.60","192.168.102.72","192.168.102.110") $argUser = "wguser9012" $argPass = "Pass.Word" Function addUser ([string]$user,[string]$pass) { # 共通 [bool]$myError = $false $hostname = hostname # アカウント作成 try { [ADSI]$Computer = "WinNT://$hostname,computer" $NewUser = $Computer.Create("User",$user) [void]$NewUser.SetPassword($pass) [void]$NewUser.SetInfo() Write-Host "addUser: Create = OK (" $hostname ")" } catch { $myError = $true Write-Host "addUser: Create = NG (" $hostname ")" } # RDS の利用設定 if($myError -eq $false) { try { $Group = $Computer.GetObject("group","Remote Desktop Users") [void]$Group.Add("WinNT://$hostname/$user") Write-Host "addUser: RDS = OK (" $hostname ")" } catch { $myError = $true Write-Host "addUser: RDS = NG (" $hostname ")" } } # パスワード無期限設定 if($myError -eq $false) { try { [ADSI]$UpdateUser = "WinNT://$hostname/$user,User" $UserFlags = $UpdateUser.Get("UserFlags") $UserFlags = $UserFlags -bor 0x10000 [void]$UpdateUser.Put("UserFlags",$UserFlags) [void]$UpdateUser.SetInfo() Write-Host "addUser: Password/DontExpire = OK (" $hostname ")" } catch { $myError = $true Write-Host "addUser: Password/DontExpire = NG (" $hostname ")" } } # return [string]($hostname + ":" + $user + ":" + $pass + ":" + !$myError) return "{0,-16}, {1,-16}, {2,-16}, {3}" -f $hostname,$user,$pass,!$myError } $ii = 0 ForEach($target In $hostList) { $ret = Invoke-Command $target -ScriptBlock ${function:addUser} -ArgumentList $argUser,$argPass ++$ii "[{0}] {1}" -f $ii,$ret }