3

PowerShell 小品 - 變更 AD 密碼

 2 years ago
source link: https://blog.darkthread.net/blog/ps-change-ad-passwd/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PowerShell 小品 - 變更 AD 密碼

calendar.svg 2022-07-07 10:25 PM comment.svg 2 eye.svg 2,247

很久沒寫 PowerShell,剛好有個需求暖暖身。

要變更 AD 密碼,最無腦的做法是找台 Windows 用該 AD 帳號登入,按 Ctrl-Alt-Del 然後點「變更密碼」:

Fig1_637928044545287524.gif

那有沒有辦法不要切換 Windows 登入帳號,直接變更其他 AD 帳號的密碼?(例如:小編持有多個公用帳號的密碼,用自己的帳號登入 Windows,修改公用 AD 帳號的密碼)

試寫了一個 PowerShell 小工具來完成這項工作。操作程序為輸入 AD 帳號(若非當下主機所在網域,則可輸入 DomainName\AccountName)、原來的密碼、輸入兩次新密碼,完成密碼變更。

完整程式如下。原理為先建立 System.DirectoryServices.AccountManagement.PrincipalContext,用 AD 帳號名稱找到 UserPrincipal,呼叫 ChangePassword(String, String) 方法變更密碼。輸入密碼部分,則借用先前學過的 PowerShell 密碼字串加密技巧

$ErrorActionPreference = 'STOP'
Add-Type -AssemblyName System.DirectoryServices.AccountManagement 

Write-Host "AD 密碼修改工具" -ForegroundColor Yellow
Write-Host "==============" -ForegroundColor Yellow
$domain = [Environment]::GetEnvironmentVariable("USERDOMAIN")
$userId = Read-Host "AD 帳號"
$p = $userId.Split('\')
if ($p.Length -eq 2) {
	$domain = $p[0]
	$userId = $p[1]
}
function decSecString($secString) {
	$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secString)
	return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
$passwd = decSecString (Read-Host "請輸入原密碼" -AsSecureString)
$passwdNew = decSecString (Read-Host "請輸入新密碼" -AsSecureString)
$passwdConfirm = decSecString (Read-Host "請再輸一次新密碼" -AsSecureString)
if ($passwdNew -ne $passwdConfirm) {
	Write-Host "新舊密碼不符" -ForegroundColor Red
	return
}
try {
	$ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain, $domain, $userId, $passwd)
}
catch {
	Write-Host $error[0].Exception.Message -ForegroundColor Yellow
	return
}
try {
	$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ctx, [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName, $userId)
}
catch {
	Write-Host $error[0].Exception.Message -ForegroundColor Cyan
	$ctx.Dispose()
	return
}
try {
	$user.ChangePassword($passwd, $passwdNew)
	Write-Host "密碼更新完畢" -ForegroundColor Green
}
catch {
	Write-Host $error[0].Exception.Message -ForegroundColor Magenta
}
$user.Dispose()
$ctx.Dispose()

變更成功的案例:

Fig2_637928044545761373.png

示範輸入不存在 AD 帳號、舊密碼不對、新密碼不符複雜度要求、新密碼兩次輸入不同時的顯示:

Fig3_637928044546274522.png

and has 2 comments

Comments

Post a comment

Comment
Name Captcha 48 - 7 =

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK