且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在脚本完成后防止 Powershell 关闭?

更新时间:2023-12-02 09:55:10

链接帖子中的方法 2 - 即,在退出脚本之前等待用户按下一个键 - 可以使用,但需要额外的努力:

Method 2 from the linked post - i.e., waiting for the user to press a key before exiting the script - can be used, but it requires additional effort:

按如下方式结束您的脚本,以便查看 $list before pause 命令提示的值:

End your script as follows in order to see the value of $list before the pause command prompts:

$list | Out-Host  # Force *synchronous* to-display output.
pause             # Wait for the user to press Enter before exiting.

注意:PowerShell 中的 pause 只是一个围绕 Read-Host 的函数包装器,如下所示: $null = Read-Host 'Press Enter tocontinue...' 所以,如果你想自定义提示字符串,直接调用Read-Host即可.

Note: pause in PowerShell is simply a function wrapper around Read-Host as follows: $null = Read-Host 'Press Enter to continue...' Therefore, if you want to customize the prompt string, call Read-Host directly.

这个答案解释了为什么使用Out-Host(或Format-Table) 在这种情况下是必要的;简而言之:

This answer explains why the use of Out-Host (or Format-Table) is necessary in this case; in short:

  • 在 PSv5+ 中,隐式应用Format-Table命令异步等待最多 300 毫秒.用于额外的管道输入,以便从输入数据中导出合适的列宽.

  • In PSv5+, an implicitly applied Format-Table command asynchronously waits for up to 300 msecs. for additional pipeline input, in an effort to derive suitable column widths from the input data.

  • 因为您使用 Write-Output 输出对象而没有预定义的格式化数据,这些数据具有 2 个属性(4 个或更少),所以会隐式选择表格输出,并且 Format-Table 在幕后异步使用.

  • Because you use Write-Output output objects without predefined formatting data that have 2 properties (4 or fewer ), tabular output is implicitly chosen, and Format-Table is used behind the scenes, asynchronously.

注意:异步行为仅适用于其类型格式化指令未预定义的输出对象(如使用 Get-FormatData 报告的那样)代码>);例如,Get-Alias 输出的 System.Management.Automation.AliasInfo 实例的输出格式是预定义的,所以 Get-别名;暂停 确实以预期的顺序产生输出.

Note: The asynchronous behavior applies only to output objects for whose types formatting instructions aren't predefined (as would be reported with Get-FormatData <fullOutputTypeName>); for instance, the output format for the System.Management.Automation.AliasInfo instances output by Get-Alias is predefined, so Get-Alias; pause does produce output in the expected sequence.

pause 命令在等待期结束之前执行,只有在您回答提示后 才会执行表格打印,之后窗口立即关闭.

The pause command executes before that waiting period has elapsed, and only after you've answered the prompt does the table print, after which point the window closes right away.

使用显式格式化命令(Out-Host 在最通用的情况下,但任何 Format-* cmdlet也会这样做)通过同步生成显示输出来避免该问题,以便在 pause 显示其提示时输出将可见.

The use of an explicit formatting command (Out-Host in the most generic case, but any Format-* cmdlet will do too) avoids that problem by producing display output synchronously, so that the output will be visible by the time pause displays its prompt.