PowerShell AD查询脚本问题:暂停执行与samaccountname搜索
Fixing Your AD User Query Script Issues
Let's tackle both of your PowerShell script problems step by step:
Problem 1: Fixing the "Press Enter to Exit" Pause
Your original script incorrectly wrapped the entire Get-ADUser command and Read-Host inside Write-Host—this caused the query to only run after the prompt, and the pause didn't work as intended. The fix is straightforward:
- Run the AD query first to display results to the console
- Use a standalone
Read-Hostcommand afterward to pause the script until the user presses Enter
Problem 2: Adding SamAccountName Fuzzy Filtering
To filter by samaccountname using your LoginName variable (matching the pattern you used for FullName), you just need to update the Get-ADUser filter to target the samaccountname attribute with your wildcard-wrapped variable.
Corrected Full Script
# Query users by full name [string]$FirstName = Read-Host "User First Name" [string]$LastName = Read-Host "User Last Name" [string]$FullName = "*$FirstName* *$LastName*" # Execute AD query and display sorted results Get-ADUser -Filter {Name -like $FullName} -Properties * | Select-Object Name, SamAccountName | Sort-Object Name # Pause for user to review results before moving on Read-Host "Press Enter to exit" # Query users by login name (samaccountname) [string]$Login = Read-Host "User Login name" [string]$LoginName = "*$Login*" # Execute AD query with samaccountname filter Get-ADUser -Filter {SamAccountName -like $LoginName} -Properties * | Select-Object Name, SamAccountName | Sort-Object Name # Pause again after showing login name results Read-Host "Press Enter to exit"
Key Details:
- Fixed Pause Behavior: The
Get-ADUsercommand now runs independently, outputs results immediately, andRead-Hostwaits for user input afterward—no more mixing commands insideWrite-Host! - SamAccountName Filter: The second query uses
{SamAccountName -like $LoginName}to apply the wildcard filter, mirroring how you filtered by full name. - Readability: I split the pipeline across multiple lines (with
|at the end of each line) to make the script easier to follow and edit later.
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

