作成 2023.03.30
更新 2023.03.30
更新 2023.03.30
ドメイン外からドメイン ユーザーのパスワードを変更する
パスワード変更に成功した後、Windows 資格情報も更新します
$target_dc = "db-dc1.db.lan"
$file_sv = "db-file1.db.lan"
$user_name = "db-user1@db.lan"
$old_pass = "old_password"
$new_pass = "new_password"
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$params = New-Object System.CodeDom.Compiler.CompilerParameters
$params.GenerateInMemory = $True
$params.TreatWarningsAsErrors = $True
$refs = @("System.dll","System.DirectoryServices.dll","System.DirectoryServices.AccountManagement.dll")
$params.ReferencedAssemblies.AddRange($refs)
# C Sharp
$txtCode = '
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
public class MyPass {
private string my_domain = "";
private bool change_result = false;
public MyPass(){}
public void SetDomain(string dns_domain){
my_domain = dns_domain;
return;
}
public string AuthTest(string upn, string pass){
try
{
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain, my_domain, upn, pass))
using(UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, upn)){ return usr.Name; }
}
catch(NullReferenceException){ return upn + " アカウントが見つかりませんでした"; }
catch(DirectoryServicesCOMException){ return "ユーザー名またはパスワードが正しくありません。"; }
catch(PrincipalServerDownException){ return "サーバーに接続できませんでした。ユーザーのドメイン名が違っているかもしれません。"; }
catch(Exception my_e){ return my_e.ToString(); }
}
public string ChangePassword(string upn, string old_pass, string new_pass){
try
{
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain, my_domain, upn, old_pass))
using(UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, upn))
{
change_result = false;
usr.ChangePassword(old_pass, new_pass);
change_result = true;
return "パスワードを変更しました。";
}
}
catch(NullReferenceException){ return upn + " アカウントが見つかりませんでした"; }
catch(DirectoryServicesCOMException){ return "ユーザー名またはパスワードが正しくありません。"; }
catch(PrincipalServerDownException){ return "サーバーに接続できませんでした。ユーザーのドメイン名が違っているかもしれません。"; }
catch(PasswordException){ return "パスワードはパスワード ポリシーの要件を満たしていません。パスワードの最短の長さ、パスワードの複雑性、およびパスワード履歴の要件を確認してください。"; }
catch(Exception my_e){ return my_e.ToString(); }
}
public bool GetChangeResult(){
return change_result;
}
}
'
$results = $provider.CompileAssemblyFromSource($params, $txtCode)
$results.Errors
$mAssembly = $results.CompiledAssembly
$i = $mAssembly.CreateInstance("MyPass")
$i.SetDomain($target_dc)
$i.AuthTest($user_name,$old_pass)
$i.ChangePassword($user_name,$old_pass,$new_pass)
if($i.GetChangeResult()){
cmdkey /add:"$file_sv" /user:"$user_name" /pass:"$new_pass"
}
タグ: ActiveDirectory