前言
簡單來說,最近有需求要先檢查使用者帳號是否存在於 DC
網域控制站內,所以就產出這篇筆記了。 😁
Option 1 執行結果
執行後,直接把結果顯示在 PowerShell 視窗中,檢查到使用者帳號存在就綠色字體顯示,檢查到使用者帳號不存在時就紅色字體顯示。
Option 2 執行結果
執行後,直接把結果寫入至筆記本檔案內,檢查到使用者帳號存在的部份匯出至「今天日期_UsersList_OK.txt」檔案內,檢查到使用者帳號不存在的部份匯出至「今天日期_UsersList_not_exist.txt」檔案。PowerShell Code
下列是這次實作的 PowerShell。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ================================================================== | |
# Author: Weithenn Wang (weithenn at weithenn.org) | |
# Version: v0.1 - June 16, 2021 | |
# Description: Check whether the user exists in AD or not | |
# ================================================================== | |
# Read users list | |
$Users_List = Get-Content -Path C:\tmp\UsersList.txt | |
$Today = Get-Date -Format "yyyyMMdd" | |
# Option 1: Check whether the user exists in AD or not | |
foreach ($User in $Users_List){ | |
If (Get-ADUser -Filter {SamAccountName -eq $User}){ | |
Write-Host "$User - OK!" -ForegroundColor Green | |
} else { | |
Write-Host "$User - account does not exist in AD" -ForegroundColor Red | |
} | |
} | |
# Option 2: Check whether the user exists in AD or not and export result | |
foreach ($User in $Users_List){ | |
If (Get-ADUser -Filter {SamAccountName -eq $User}){ | |
$User | Out-File -FilePath C:\PowerCLI\"$Today"_UsersList_OK.txt -Append | |
} else { | |
$User | Out-File -FilePath C:\PowerCLI\"$Today"_UsersList_not_exist.txt -Append | |
} | |
} |