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

PowerShell中Out-GridView选择后后续AD命令无响应问题求助

PowerShell AD脚本问题修复

脚本1:用户密码重置脚本问题修复

原问题分析

  • 第一行Get-ADUser末尾多余的管道符|导致语法错误,脚本执行中断
  • Set-ADAccountPassword的-NewPassword参数要求接收SecureString类型,直接传入Read-Host返回的普通字符串会执行失败
  • 字符串插值语法错误:$choice.DistinguishedName在双引号中无法正确解析对象属性,需用子表达式格式

修正后的脚本

Import-Module ActiveDirectory
$x = Read-Host -Prompt "Enter Search Query for Name"
$choice = Get-ADUser -Filter "SamAccountName -like '*$x*'" -Properties DisplayName | 
          Select-Object Name, DistinguishedName | 
          Out-GridView -PassThru

if($choice) { 
    foreach($user in $choice) {
        $user.DistinguishedName
        Get-ADUser -Identity $user.DistinguishedName -Properties SamAccountName, Enabled, LockedOut, AccountLockoutTime, BadLogonCount | 
        Select-Object SamAccountName, Enabled, LockedOut, AccountLockoutTime, BadLogonCount | 
        Out-Host
        
        $NewPassword = Read-Host -Prompt "Enter New Password for $($user.DistinguishedName)" -AsSecureString
        Set-ADAccountPassword -Server *REDACTED* -Identity $user.DistinguishedName -NewPassword $NewPassword -Reset
    }
}
else { 
    exit
}

关键修复点

  • 移除多余管道符,统一Filter的通配符规则
  • 使用Read-Host -AsSecureString直接生成符合要求的安全字符串
  • 加入foreach循环支持多选用户场景
  • 修正字符串插值为$($user.DistinguishedName)确保属性正确解析
  • 优化Get-ADUser的-Properties参数,仅指定需要的属性提升执行效率

脚本2:锁定用户解锁脚本问题修复

原问题分析

  • 未处理Out-GridView多选场景:当用户选择多个锁定用户时,$choice为数组,直接访问$choice.DistinguishedName会返回所有用户的DN数组,导致后续命令执行异常
  • 字符串插值语法错误,无法正确解析对象属性

修正后的脚本

Import-Module ActiveDirectory
$ous = Search-ADAccount -LockedOut -UsersOnly 
$choice = $ous | Select-Object Name, DistinguishedName | Out-GridView -PassThru

if($choice) { 
    foreach($user in $choice) {
        $user.DistinguishedName
        Get-ADUser -Identity $user.DistinguishedName -Properties SamAccountName, Enabled, LockedOut, AccountLockoutTime, BadLogonCount | 
        Select-Object SamAccountName, Enabled, LockedOut, AccountLockoutTime, BadLogonCount | 
        Out-Host
        
        Write-Host "Unlocking $($user.DistinguishedName)"
        Unlock-ADAccount -Server *REDACTED* -Identity $user.DistinguishedName
    }
}
else { 
    exit
}

关键修复点

  • 加入foreach循环遍历选中的每个用户,支持多选解锁
  • 修正字符串插值为$($user.DistinguishedName)
  • 优化Get-ADUser的-Properties参数,仅加载必要属性

内容的提问来源于stack exchange,提问作者Vincent

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:20:02