批量查询PC用户时设置2秒超时跳过及提速方法咨询
解决方法
一、修正原脚本的语法错误
你原命令里的get-content = "C:\Users\Public\Documents\CSV\tfiles\Computernames.txt"多了一个等号,正确写法是:
$Computers = Get-Content "C:\Users\Public\Documents\CSV\tfiles\Computernames.txt"
二、给单台查询添加2秒超时
可以用System.Diagnostics.Process类执行query user命令并设置超时,无响应则直接跳过:
$Computers = Get-Content "C:\Users\Public\Documents\CSV\tfiles\Computernames.txt" $timeoutSeconds = 2 foreach ($Computer in $Computers) { $process = New-Object System.Diagnostics.Process $process.StartInfo.FileName = "query.exe" $process.StartInfo.Arguments = "user /server:$Computer" $process.StartInfo.RedirectStandardOutput = $true $process.StartInfo.RedirectStandardError = $true $process.StartInfo.UseShellExecute = $false $process.StartInfo.CreateNoWindow = $true $process.Start() | Out-Null # 等待指定超时时间,判断进程是否完成 if ($process.WaitForExit($timeoutSeconds * 1000)) { Write-Host "=== $Computer 的用户信息 ===" $process.StandardOutput.ReadToEnd() } else { # 超时终止进程并提示 $process.Kill() Write-Warning "$Computer 无响应,已跳过" } }
三、更快的并行处理方案
串行处理2000台电脑效率极低,用PowerShell 7+的ForEach-Object -Parallel实现并行查询,能大幅提升速度,同时保留超时逻辑:
$Computers = Get-Content "C:\Users\Public\Documents\CSV\tfiles\Computernames.txt" $timeoutSeconds = 2 $Computers | ForEach-Object -Parallel { $Computer = $_ $timeout = $using:timeoutSeconds $process = New-Object System.Diagnostics.Process $process.StartInfo.FileName = "query.exe" $process.StartInfo.Arguments = "user /server:$Computer" $process.StartInfo.RedirectStandardOutput = $true $process.StartInfo.RedirectStandardError = $true $process.StartInfo.UseShellExecute = $false $process.StartInfo.CreateNoWindow = $true $process.Start() | Out-Null if ($process.WaitForExit($timeout * 1000)) { [PSCustomObject]@{ ComputerName = $Computer UserInfo = $process.StandardOutput.ReadToEnd() Status = "Success" } } else { $process.Kill() [PSCustomObject]@{ ComputerName = $Computer UserInfo = $null Status = "Timeout" } } } -ThrottleLimit 50 # 控制并行数,避免网络过载,可根据环境调整为30-100
四、其他优化建议
- 提前过滤无效主机:先通过
Test-Connection快速筛选能ping通的主机,减少无效查询:$validComputers = $Computers | Where-Object { Test-Connection -ComputerName $_ -Count 1 -TimeoutSeconds 1 -Quiet } - 结构化输出:把结果保存为CSV方便后续分析,可在并行脚本末尾追加:
| Export-Csv -Path "C:\UserQueryResults.csv" -NoTypeInformation
内容的提问来源于stack exchange,提问作者Toon
相关产品推荐
相关产品推荐

