如何在PowerShell AD操作脚本中弹出凭据输入提示?
在PowerShell脚本处理AD操作时添加凭据输入提示的解决方法
问题说明
你需要在现有PowerShell脚本中添加凭据输入提示,用于本地管理员组的AD相关操作,但之前尝试的两种方法均未成功:
- 用外部脚本收集凭据后启动目标脚本,脚本无法正常启动
- 尝试给
[ADSI]添加-Credential参数,但该命令不支持此参数
现有脚本核心问题
原脚本中Invoke-Command和[ADSI]操作默认使用当前运行上下文权限,未传入指定凭据;同时外部启动脚本的路径格式可能存在问题。
解决方案
1. 全局获取凭据并复用
在脚本开头添加凭据输入逻辑,后续所有需要权限的操作统一使用该凭据:
# 弹出凭据输入对话框 $cred = Get-Credential -Message "请输入用于AD操作的权限凭据"
2. 修复Invoke-Command的凭据传递
为Invoke-Command添加-Credential参数,并增加错误处理避免单台机器异常中断整个脚本:
$Administrators = Invoke-Command -ComputerName $HN -Credential $cred -ScriptBlock { Get-LocalGroupMember -Name "administrators" } -ErrorAction SilentlyContinue
3. 为ADSI操作添加凭据支持
[ADSI]快捷方式不支持直接传凭据,需改用System.DirectoryServices.DirectoryEntry类显式指定凭据:
替换原脚本中的ADSI操作代码段:
$adminGroupPath = "WinNT://$IPA/Administrators,group" $userPath = "WinNT://USA/EAGANACE,user" # 创建带凭据的组对象 $adminGroup = New-Object System.DirectoryServices.DirectoryEntry( $adminGroupPath, $cred.UserName, $cred.GetNetworkCredential().Password ) # 创建带凭据的用户对象 $user = New-Object System.DirectoryServices.DirectoryEntry( $userPath, $cred.UserName, $cred.GetNetworkCredential().Password ) $adminGroup.Invoke("Add", $user.Path) Write-Host 'Admin has been added as an administrator'
4. 修复外部启动脚本的路径问题
若仍需用外部脚本启动目标脚本,需处理路径带空格的情况,给脚本路径添加双引号:
$Cred = Get-Credential $ScriptLocation = "C:\Your\Script\Path\Script.ps1" # 给脚本路径加双引号,避免空格导致参数解析错误 Start-Process -Credential $Cred -FilePath "Powershell.exe" -ArgumentList "-file `"$Scriptlocation`""
完整修改后的脚本
# 弹出凭据输入对话框 $cred = Get-Credential -Message "请输入用于AD操作的权限凭据" While($true){ Clear-Host $IPSet = Ping-IPRange -StartAddress 56.192.87.200 -EndAddress 56.192.87.254 -Interval 60 $IPSet | Select-object IPAddress | foreach { $IPA = $_.IPAddress try{ $HN = [System.Net.Dns]::GetHostByAddress($IPA) | Select-Object -ExpandProperty Hostname $Administrators = Invoke-Command -ComputerName $HN -Credential $cred -ScriptBlock { Get-LocalGroupMember -Name "administrators" } -ErrorAction Stop if ($Administrators -like '*Admin*') { Write-Host "$HN - Admin is already an administrator" } else { $adminGroupPath = "WinNT://$IPA/Administrators,group" $userPath = "WinNT://USA/EAGANACE,user" $adminGroup = New-Object System.DirectoryServices.DirectoryEntry( $adminGroupPath, $cred.UserName, $cred.GetNetworkCredential().Password ) $user = New-Object System.DirectoryServices.DirectoryEntry( $userPath, $cred.UserName, $cred.GetNetworkCredential().Password ) $adminGroup.Invoke("Add", $user.Path) Write-Host "$HN - Admin has been added as an administrator" } } catch{ Write-Host "$IPA - 操作失败:$_" -ForegroundColor Red } } }
注意事项
- 确保输入的凭据对目标机器拥有管理员权限,可修改本地管理员组
- 确认
Ping-IPRange自定义函数已加载到当前会话 - 添加
try-catch块可单独处理单台机器的异常,避免中断整个循环
内容的提问来源于stack exchange,提问作者ThePostMan
相关产品推荐
相关产品推荐

