You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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-Host command 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-ADUser command now runs independently, outputs results immediately, and Read-Host waits for user input afterward—no more mixing commands inside Write-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:37:34