Search code examples
powershellforeachpause

Powershell foreach executing after pause


I created a script to read a list of names and translate them to IP by using "Resolve-DnsName". I want users to just double click the script and read the output.

cls
Write-Host -ForegroundColor Green -BackgroundColor DarkRed "
 ______________________________
|X      | Y     | Z            |
|-------+ ------+--------------|
|F2M1   | 49621 |esbsa9908ee43 |
|F2M2   | 47546 |esbsa009908jc1|
|F2M3   |xxxxxxx|7417191543366 |
|F2M4   | 47516 |esbsa9908ee18 |
|F2M5   | 47385 |7417191543116 |
|Capital| 86658 |7417191543242 |
|______________________________|"
Write-Host "`n`n"


$estacoes = @(
    'esbsa9908ee43',
    'esbsa009908jc1',
    '7417191543366',
    'esbsa9908ee18',
    '7417191543116',
    '7417191543242'
)

ForEach ($estacao in $estacoes){
    Resolve-DnsName -ErrorAction Continue -Type A -QuickTimeout -Name $estacao | Select-Object Name,IpAddress
    }

Pause

It happens that the "pause" command at the end is being executed before "foreach".

 ______________________________
|X      | Y     | Z            |
|-------+ ------+--------------|
|F2M1   | 49621 |esbsa9908ee43 |
|F2M2   | 47546 |esbsa009908jc1|
|F2M3   |xxxxxxx|7417191543366 |
|F2M4   | 47516 |esbsa9908ee18 |
|F2M5   | 47385 |7417191543116 |
|Capital| 86658 |7417191543242 |
|______________________________|


Press Enter to continue...:


Name           IPAddress
----           ---------
esbsa9908ee43  172.18.18.215
esbsa009908jc1 172.18.18.44
7417191543366  172.18.18.18
esbsa9908ee18  172.18.18.21
7417191543116  172.18.18.126
7417191543242  172.30.165.50

I can't seem to find a reason for that. Can you guys help out?


Solution

  • It looks similar to the funny things that happen with pipe output and write-host output, where the write-host output will come out first even though it's run after the pipeline. Here's one way to change the order of the output:

    $estacoes = echo microsoft.com yahoo.com
    $result = ForEach ($estacao in $estacoes){
        Resolve-DnsName -ErrorAction Continue -Type A -QuickTimeout -Name $estacao | 
          Select-Object Name,IpAddress 
        }
    
    $result | format-table
    
    pause
    
    # didn't work
    # 'Press Enter to continue...:'
    # [void][console]::readkey()