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

PowerShell如何确保当前行执行完成后再运行下一行?解决执行顺序错乱问题

PowerShell PowerView脚本执行顺序异常修复方案

问题原因

这个现象是PowerShell默认的输出流缓冲渲染机制导致的:Select-Object生成的自定义属性对象会进入成功输出流,PowerShell为了统一优化输出格式,会等待后续所有同流的输出内容生成完成后再统一排版打印到控制台,而Invoke-ACLScanner属于高耗时操作,最终就出现了扫描逻辑先跑完、才打印前面用户列表的顺序错乱问题。

修复方法

在需要立即输出到控制台的语句后追加| Out-Host,强制该部分输出直接渲染到控制台,不参与后续管道缓冲等待,修改后的代码如下:

cd C:\;

. .\PowerView.ps1;

Write-Output "Users:";
$Users = Get-DomainUser -UACFilter NOT_ACCOUNTDISABLE;
# 加Out-Host强制立即输出用户列表
$Users | Select-Object -Property samaccountname, description | Out-Host;
Write-Output "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=";
Write-Output ""

Write-Output "ACL:";
# 加Out-Host强制立即输出用户名列表
$Users | select -ExpandProperty name | Out-Host;
# 原代码中$UsersArray为冗余变量,可直接遍历$Users
foreach ($user in $Users) {
    Invoke-ACLScanner -ResolveGUIDs | ?{($_.IdentityReference -match "$user") -or ($_.IdentityReferenceName -match "$user")};
}

如果仍然存在顺序问题,可以额外在需要强制刷新的位置加[Console]::Out.Flush()手动刷新控制台输出缓冲区。

内容的提问来源于stack exchange,提问作者hosam.shafik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:06:03