PowerShell无控制台程序弹出数组计数弹窗,如何消除?
问题解决:编译后PowerShell脚本弹出额外数组大小窗口
问题原因
[System.Collections.ArrayList]的Add()方法会返回元素添加后的索引值(即当前数组的大小),在无控制台模式编译运行时,这个返回值未被处理,被当作输出触发了额外窗口显示该数值。
解决方案
只需丢弃Add()方法的返回值,避免产生输出即可,以下是三种常用实现方式:
方式1:使用[void]前缀
修改verifyProcessEnd函数内的添加逻辑:
if($finishedList -notcontains($name)){ [void]$finishedList.Add($name) }
方式2:将结果赋值给$null
if($finishedList -notcontains($name)){ $null = $finishedList.Add($name) }
方式3:通过管道输出到Out-Null
if($finishedList -notcontains($name)){ $finishedList.Add($name) | Out-Null }
修改后的完整脚本
#verify that all processes have ended function verifyProcessEnd{ DO{ foreach($name in $processList){ if((Get-Process $name -ErrorAction SilentlyContinue) -eq $null){ #fill our finished processes list if($finishedList -notcontains($name)){ [void]$finishedList.Add($name) } } } }while($finishedList.Count -ne $processList.Count) } #____________________________________ Main ____________________________________# #get the list of processes to check for - these must match the service name (minus extension) in task manager [System.Collections.ArrayList]$processList = 'WINWORD', 'msedge' #can be changed to any processes # create a new list for finished processes. [System.Collections.ArrayList]$finishedList = @() $wshell = New-Object -ComObject Wscript.Shell $wshell.Popup("Please wait for all processes to end before starting the program", 10, "Done",0x1) verifyProcessEnd $wshell.Popup("All startup processes have completed. It is safe to start the program", 10, "Done",0x1)
内容的提问来源于stack exchange,提问作者AngelOfChaos
相关产品推荐
相关产品推荐

