为什么 "Read-host" 部分 运行 位于代码之前?

Why is the "Read-host" section running before the code?

我只想要一个 .ps1 文件,它将 运行 一行简单的 powershell 但不会立即关闭。

我试过"read-host -prompt "“”,但它在代码 运行 之前显示,然后仍然立即关闭

get-appxpackage -allusers | select name 

read-host -prompt "Press enter to exit"

我希望结果是 运行 文件,然后有机会在按某些东西退出之前读取 powershell window 中的输出。但实际输出是在代码运行之前提示退出,然后运行s通过输出并关闭

执行完这行代码后:

get-appxpackage -allusers | select name 

您将有一些 "pending" 对象准备好 return 到 Powershell 管道输出流。在 Read-Host 完成之前,无法将对象发送到管道(因为 Powershell 会将这些对象视为 ps1 文件的 "output")。 Read-Host 完成后,对象被发送到管道(通过输出流)。由于那里没有其他 cmdlet(使用您 ps1 文件的输出),Powershell 的默认行为是将管道内容输出到 Powershell 主机。

正如上面评论中提到的@Lee_Daily,添加Out-Host会将get-appxpackage -allusers | select name的输出发送到Powershell主机。因此 get-appxpackage -allusers | select name | out-host 没有对象在输出流中排队等待进一步的管道操作。

我建议您查看以下来源:

这些是您必须了解的基本 Powershell 概念。

希望对您有所帮助。

继续 Lee 和 Moerwald 所说的话。

另一种实时流式传输的方法是使用 ForEach 或 ForEach-Object,它也比 Out-Host 方法更高效,因为它不会默认写入屏幕。如果后者的性能 v 屏幕写入对您很重要。如果不想要Out-Host的屏幕输出,就送Null。

# Using Out-Host

Measure-Command {
    get-appxpackage -allusers | 
    select name | Out-Host
}



Name                                             
----                                             
1527c705-...            
...           
InputApp                                         
Microsoft.AAD.BrokerPlugin                       
Microsoft.AccountsControl                        
...                            


# Results

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
*** Milliseconds      : 643 ***
Ticks             : 6431627
TotalDays         : 7.44401273148148E-06
TotalHours        : 0.000178656305555556
TotalMinutes      : 0.0107193783333333
TotalSeconds      : 0.6431627
TotalMilliseconds : 643.1627



# User ForEach in a script Block

Measure-Command {
    & { foreach ($item in get-appxpackage -allusers | select name)
    { "processing $item"}}
}


# Results

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
*** Milliseconds      : 385 ***
Ticks             : 3858318
TotalDays         : 4.46564583333333E-06
TotalHours        : 0.0001071755
TotalMinutes      : 0.00643053
TotalSeconds      : 0.3858318
TotalMilliseconds : 385.8318



# Standard ForEach-Object

Measure-Command {
    get-appxpackage -allusers | 
    ForEach-Object {select name}
}


# Results

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
*** Milliseconds      : 498 ***
Ticks             : 4988494
TotalDays         : 5.77371990740741E-06
TotalHours        : 0.000138569277777778
TotalMinutes      : 0.00831415666666667
TotalSeconds      : 0.4988494
TotalMilliseconds : 498.8494