PowerShell 小品
很久沒寫 PowerShell,剛好有個需求暖暖身。
要變更 AD 密碼,最無腦的做法是找台 Windows 用該 AD 帳號登入,按 Ctrl-Alt-Del 然後點「變更密碼」:
那有沒有辦法不要切換 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()
變更成功的案例:
示範輸入不存在 AD 帳號、舊密碼不對、新密碼不符複雜度要求、新密碼兩次輸入不同時的顯示:
Example of using PowerShell to change AD password.
