我试图独自寻找解决方案,但现在我没有主意了。我写了一个脚本来检查计算机上是否安装了Erlang:
# Check if a Software ins installed
function Check_Program_Installed($programName) {
$x86_check = ((Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall") |
Get-ItemProperty |
Where-Object {$_.DisplayName -like "*$programName*" } |
Select-Object -Property DisplayName, UninstallString)
if(Test-Path 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall')
{
$x64_check = ((Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall") |
Get-ItemProperty |
Where-Object {$_.DisplayName -like "*$programName*" } |
Select-Object -Property DisplayName, UninstallString)
}
if ($x86_check -and $x64_check -eq $null){
write-host "$programName is not installed on this computer" -ForegroundColor Green
#continue
}
elseif ($x86_check -or $x64_check -ne $null){
write-host "On this computer is installed " -ForegroundColor Red
$x86_check
$x64_check
}
}
# Erlang check
Write-Host "Checking if Erlang exist " -NoNewline
Check_Program_Installed("Erlang")
Write-Host "The End: the script ends here" -ForegroundColor Yellow
但是如果我执行它的结果是最后一行在Check_Program_Installed("Erlang")
之前执行。为什么PowerShell不遵守步骤优先级?
Checking if Erlang exist On this computer is installed
The End: the script ends here
DisplayName UninstallString
----------- ---------------
Erlang OTP 21 (10.2) C:\Program Files\erl10.2\Uninstall.exe
答案 0 :(得分:2)
我尝试复制您的代码并对其进行测试,但是我无法使实际的Check_Program_Installed
函数正常工作,因此我很难进行验证。
但是,对于PowerShell,了解管道很重要。
通常,您所做的所有操作都会将其发送到管道,并按照管道获取的顺序显示在控制台中。
但是,Write-Host不会将您的文本发送到管道,而是直接将其发送到控制台,因此这可能是一种简单的竞争条件,其中文本到达控制台的速度比管道对象快。
如果您尝试使用Write-Output
而不是Write-Host
进行测试,我猜您会以正确的顺序得到它,因为Write-Output
通过管道将对象发送到控制台。
答案 1 :(得分:2)
只需在最后添加Format-Table到$ x86_check和$ 64_check。链接答案:https://social.technet.microsoft.com/Forums/en-US/5f88f7c9-fbce-4c45-a2fa-806d512a0233/powershell-output-wrong-order?forum=ITCG
# Check if a Software ins installed
function Check_Program_Installed($programName) {
$x86_check = ((Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall") |
Get-ItemProperty |
Where-Object {$_.DisplayName -like "*$programName*" } |
Select-Object -Property DisplayName, UninstallString) | Format-Table
if(Test-Path 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall')
{
$x64_check = ((Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall") |
Get-ItemProperty |
Where-Object {$_.DisplayName -like "*$programName*" } |
Select-Object -Property DisplayName, UninstallString) | Format-Table
}
if ($x86_check -and $x64_check -eq $null){
write-host "$programName is not installed on this computer" -ForegroundColor Green
#continue
}
elseif ($x86_check -or $x64_check -ne $null){
write-host "On this computer is installed " -ForegroundColor Red
$x86_check
$x64_check
}
}
# Erlang check
Write-Host "Checking if Erlang exist " -NoNewline
Check_Program_Installed("Erlang")
Write-Host "The End: the script ends here" -ForegroundColor Yellow