question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Powershell v7.1 - Invoke-WebRequest not clearing in script when using Clear-Host

See original GitHub issue

After upgrading my script to from Powershell 7.0.3 to 7.1 whenever I use invoke-webrequest and do a clear-host it still leaves the following data in the console.

Web request status Web request completed. (Number of bytes processed: 9738485)

This is a part of a larger script that is proprietary, I removed some info from the script for privacy but the example I provided should provide enough insight into the issue. Anywhere an invoke-webrequest is used, this issue occurs, I just used Ethr as an example.

Steps to reproduce


Function Build-Menu (){
    
    Param(
        [Parameter(Mandatory=$True)][String]$MenuTitle,
        [Parameter(Mandatory=$True)][array]$MenuOptions
    )

    $MaxValue = $MenuOptions.count-1
    $Selection = 0
    $EnterPressed = $False
    
    Clear-Host

    While($EnterPressed -eq $False){
        $MenuTitleLength = ($MenuTitle | Measure-Object -Character).Characters
        if ($MenuTitleLength -eq 16) {
            $Space = 7
        }
        if ($MenuTitleLength -gt 16) {
        $Difference = ($MenuTitleLength - 16)
        $Space = (7 - $Difference)

        } else {
            $Difference = (16 - $MenuTitleLength)
            $Space = (7 + $Difference)
        }
        $MenuTitleValue = "::       $MenuTitle" + " " * $Space + "::"
        Clear-Host
        Write-Host "::::::::::::::::::::::::::::::::::"
        Write-Host -ForegroundColor Green "::       Demo System       ::"
        Write-Host -ForegroundColor White "$MenuTitleValue"
        Write-Host "::::::::::::::::::::::::::::::::::"
        Write-Host ""

        For ($i=0; $i -le $MaxValue; $i++){
            
            If ($i -eq $Selection){
                Write-Host -BackgroundColor Cyan -ForegroundColor Black "[ $($MenuOptions[$i]) ]"
            } Else {
                Write-Host "  $($MenuOptions[$i])  "
            }

        }

        $KeyInput = $host.ui.rawui.readkey("NoEcho,IncludeKeyDown").virtualkeycode

        Switch($KeyInput){
            13{
                $EnterPressed = $True
                Return $Selection
                Clear-Host
                break
            }

            38{
                If ($Selection -eq 0){
                    $Selection = $MaxValue
                } Else {
                    $Selection -= 1
                }
                Clear-Host
                break
            }

            40{
                If ($Selection -eq $MaxValue){
                    $Selection = 0
                } Else {
                    $Selection +=1
                }
                Clear-Host
                break
            }
            Default{
                Clear-Host
            }
        }
    }
}



function Get-File($filename,$url,$outpath,$alturl) {
    Clear-Host
    Write-Host "Downloading" $filename"..."
    try {
        if ($alturl) {
            try {
                Invoke-WebRequest -Uri $url -OutFile $outpath
            } catch {
                Invoke-WebRequest -Uri $alturl -OutFile $outpath
            }
        }
        else {
            Invoke-WebRequest -Uri $url -OutFile $outpath
        }
        Write-Host $filename "has downloaded!"
    } catch {
        Write-Host -ForegroundColor Red $filename "download failed!"
    }
}

do {
                    $MenuArray = @(
                        "Run SpeedTest",
                        "Show Network Share Info", 
                        "Get Users Mapped Shares",
                        "Run Lan SpeedTest (iperf)",
                        "Run Advanced IP Scanner",
                        "Run WOL (Wake On LAN) Utility",
                        "Use Ethr",
                        "Exit"
                    )
                    Clear-Host
                    $MenuChoice = Build-Menu -MenuTitle "Network Tools" -MenuOptions $MenuArray
                    #Header -MenuTitle "Network Tools" -Menu $MenuArray -Confirm $True

                    if ($MenuChoice -eq '0') {
                        Clear-Host
                        Get-File -filename "SpeedTest" -url "#" -outpath "C:\Flexible-Toolkit\SpeedTest.exe" -alturl "#"
                        if (Test-Path -Path "C:\Flexible-Toolkit\SpeedTest") {
                            Remove-Item -Path "C:\Flexible-Toolkit\SpeedTest\" -Recurse -Force
                            Clear-Host
                        }
                        Unblock-File "C:\Flexible-Toolkit\speedtest.exe" -ErrorAction SilentlyContinue
                        C:\Flexible-Toolkit\speedtest.exe --accept-license
                        Write-Host -ForegroundColor Green "Press Enter to continue."
                        Read-Host | Out-Null
                        Remove-Item -Path "C:\Flexible-Toolkit\SpeedTest.exe" -Force
                    }

                    if ($MenuChoice -eq '1') {
                        if($Legacy -eq "false") {
                            Clear-Host
                            Write-Host -ForegroundColor White "Shares on this device"
                            Write-Host "-------------------------------------------"
                            Write-Host ""
                            Get-SmbShare | Select-Object Name, Path, Description | Format-Table
                            Write-Host "-------------------------------------------"
                            Write-Host -ForegroundColor White "Active sessions on device (Outbound)"
                            Write-Host ""
                            Get-SmbConnection | Select-Object ServerName, ShareName, UserName, Credential, NumOpens | Format-Table
                            Write-Host -ForegroundColor White "Users connected to this device (Inbound)"
                            Get-SmbSession | Format-Table
                            Write-Host "-------------------------------------------"
                            Write-Host -ForegroundColor White "Open Files (Inbound)"
                            Write-Host ""
                            Get-SmbOpenFile | Format-Table
                            Write-Host ""
                        } else {
                            Clear-Host
                            Write-Host -ForegroundColor Red "Not supported on this OS."
                        }
                        Write-Host "-------------------------------------------"
                        Write-Host -ForegroundColor Green "Press Enter to continue."
                        Read-Host | Out-Null
                        
                    }

                    if ($MenuChoice -eq '2') {
                        do {
                            Clear-Host
                            $Username = Read-Host "Enter Username "
                            $isDomain = Read-Host "Is this a domain account?" "[Y / N]"
                            if ($isDomain -eq 'y') {
                                $domain = Read-Host "What is the domain? (DO NOT incude .local,.com etc...)"
                            }
                            $areSure = Read-Host "Username = $Username. Are you sure?" "[Y / N]"
                        } while ($areSure -ne 'y')
                        if ($isDomain -eq 'y') {
                            #$domain = (Get-WmiObject Win32_NTDomain).DomainName
                            $domain = $domain
                        }
                        else {
                            $domain = $env:computername
                        }
                        $TargetKey = ([wmi] "win32_userAccount.Domain='$domain',Name='$Username'").sid
                        Write-Host "Users Profile Key = $TargetKey"
                        Clear-Host
                        if (Test-Path -Path "REGISTRY::HKEY_USERS\$TargetKey\Network\") {
                            Write-Host -ForegroundColor Green "Below are the drives the user has mapped manually."
                            Get-ChildItem "REGISTRY::HKEY_USERS\$TargetKey\Network\" -Recurse | Format-Table
                            if ($Legacy -eq "false") {
                                Write-Host -ForegroundColor Green "Below are the drives that were automatically mapped for the user/system."
                                $systemMapped = (Get-CimInstance Win32_MappedLogicalDisk | Select-Object name, providername) | out-string
                                Write-Host $systemMapped
                            }
                            Write-Host -ForegroundColor Green "Please see $Username's mapped drives above."
                            Write-Host -ForegroundColor Green "If there's nothing above the user may not have mapped drives."
                        } 
                        else {
                            Write-Host -ForegroundColor Red "Profile not found."
                            if($Legacy -eq "false") {
                                Write-Host -ForegroundColor Red "However we listed any mapped drives that might have been added automatically for the user/system below."
                                $systemMapped = (Get-CimInstance Win32_MappedLogicalDisk | Select-Object name, providername) | out-string
                                Write-Host $systemMapped
                            }
                        }
                        Write-Host -ForegroundColor Green "Press Enter to continue."
                        Read-Host | Out-Null
                    }

                    if ($MenuChoice -eq '3') {
                        Clear-Host
                        Get-File -filename "iperf3" -url "https://iperf.fr/download/windows/iperf-3.1.3-win64.zip" -outpath "C:\Flexible-Toolkit\iperf-3.1.3-win64.zip"
                        Expand-Archive -Path "C:\Flexible-Toolkit\iperf-3.1.3-win64.zip" -DestinationPath "C:\Flexible-Toolkit\" -Force
                        Write-Host "iperf3 Downloaded"
                        Clear-Host
                        do{
                            $MenuArray = @(
                                "Setup Target (Destination)",
                                "Initiate Test to Target (Source)", 
                                "Exit"
                            )
                            Clear-Host
                            $MenuChoice = Build-Menu -MenuTitle "LAN SpeedTest Tools" -MenuOptions $MenuArray
                            #Header -MenuTitle "LAN SpeedTest Tools" -Menu $MenuArray -Confirm $True

                            if ($MenuChoice -eq '0') {
                                Clear-Host
                                Start-Process "C:\Flexible-Toolkit\iperf-3.1.3-win64\iperf3.exe" -ArgumentList "-s"
                                Write-Host -ForegroundColor Green "A new window should have launched with the tool running."
                                Write-Host -ForegroundColor Green "This device is now ready to take connections from the Source Device."
                                Write-Host -ForegroundColor Green "You now need to run this script on the Source device and initiate the test."
                                Write-Host -ForegroundColor Red "Do NOT press continue until you are done with the test as it will delete required files."
                                Write-Host -ForegroundColor Green "Press Enter to continue."
                                Read-Host | Out-Null
                                Stop-Process -Name "iperf3" -Force
                            }

                            if ($MenuChoice -eq '1') {
                                Clear-Host
                                $localIP = Read-Host ("Enter IP address of target/destination device ")
                                C:\Flexible-Toolkit\iperf-3.1.3-win64\iperf3.exe -c $localIP
                                Write-Host -ForegroundColor Red "Do Not press continue until you are done with the test as it will delete required files."
                                Write-Host -ForegroundColor Green "Press Enter to continue."
                                Read-Host | Out-Null
                            }

                        } while ($MenuChoice -ne (($MenuArray.Length -1).ToString()))
                        $MenuChoice = $null
                    }

                    if ($MenuChoice -eq '4') {
                        Clear-Host
                        Get-File -filename "Advanced IP Scanner" -url "https://www.advanced-ip-scanner.com/download/Advanced_IP_Scanner_2.5.3850.exe" -outpath "C:\Flexible-Toolkit\AdvancedIPScanner.exe"
                        Start-Process -FilePath "C:\Flexible-Toolkit\AdvancedIPScanner.exe"
                        Write-Host -ForegroundColor Green "Advanced IP Scanner should be running."
                        Write-Host -ForegroundColor Green "Press Enter to continue."
                        Read-Host | Out-Null
                    }

                    if ($MenuChoice -eq '5') {
                        Clear-Host
                        Get-File -filename "WOL.exe Utility" -url "#" -outpath "C:\Flexible-Toolkit\WOL.exe"
                        Clear-Host
                        $WOLMacAddress = Read-Host "Enter the MAC Address of the offline machine"
                        C:\Flexible-Toolkit\WOL.exe $WOLMacAddress
                        Write-Host -ForegroundColor Green "Press Enter to continue."
                        Read-Host | Out-Null
                    }

                    if ($MenuChoice -eq '6') {
                        Clear-Host
                        Get-File -filename "Ethr" -url "https://github.com/microsoft/ethr/releases/latest/download/ethr_windows.zip" -outpath "C:\Flexible-Toolkit\ethr.zip"
                        Expand-Archive -Path "C:\Flexible-Toolkit\ethr.zip" -DestinationPath "C:\Flexible-Toolkit\" -Force
                        Write-Host "Ethr Downloaded"
                        Clear-Host
                        do{
                            $MenuArray = @(
                                "Setup Server (Destination)",
                                "Setup Client (Source)",
                                "Measure TCP Connection Setup Latency to Website",
                                "Measure ICMP ping latency to Website",
                                "Exit"
                            )
                            Clear-Host
                            $MenuChoice = Build-Menu -MenuTitle "Ethr Menu" -MenuOptions $MenuArray
                            #Header -MenuTitle "LAN SpeedTest Tools" -Menu $MenuArray -Confirm $True

                            if ($MenuChoice -eq '0') {
                                Clear-Host
                                Start-Process -FilePath "powershell.exe" -ArgumentList 'C:\Flexible-Toolkit\ethr.exe -s -ui'
                                Write-Host -ForegroundColor Green "A new window should have launched with the tool running."
                                Write-Host -ForegroundColor Green "This device is now ready to take connections from the client device."
                                Write-Host -ForegroundColor Green "You now need to run this script on the client device and initiate the test."
                                Write-Host -ForegroundColor Red "Do NOT press continue until you are done with the test as it will delete required files."
                                Write-Host -ForegroundColor Green "Press Enter to continue."
                                Read-Host | Out-Null
                                Stop-Process -Name "ethr" -Force
                            }

                            if ($MenuChoice -eq '1') {
                                Clear-Host
                                $localIP = Read-Host ("Enter IP address of the device running Ethr server")
                                Start-Process -FilePath "powershell.exe" -ArgumentList 'C:\Flexible-Toolkit\ethr.exe -s -ui' $localIP
                                Write-Host -ForegroundColor Red "Do Not press continue until you are done with the test as it will delete required files."
                                Write-Host -ForegroundColor Green "Press Enter to continue."
                                Read-Host | Out-Null
                            }

                        } while ($MenuChoice -ne (($MenuArray.Length -1).ToString()))
                        $MenuChoice = $null
                    }


                } while ($MenuChoice -ne (($MenuArray.Length -1).ToString()))
                $MenuChoice = $null


Expected behavior

Launch script, select "Use Ethr" downloads file, clears screen, and builds a new menu. (This is from PWSH v7.0.3)

image image

Actual behavior

Launch script, select "Use Ethr" downloads file, screen doesn't fully clear and menu gets messed up.  If you press any keys it expands the window (seen in screenshot 3).

image image image

Environment data

Name                           Value
----                           -----
PSVersion                      7.1.0
PSEdition                      Core
GitCommitId                    7.1.0
OS                             Microsoft Windows 10.0.19042
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0


The last tested version of PowerShell that works.

Name                           Value
----                           -----
PSVersion                      7.0.3
PSEdition                      Core
GitCommitId                    7.0.3
OS                             Microsoft Windows 10.0.19042
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:11

github_iconTop GitHub Comments

1reaction
HotCakeXcommented, Jan 27, 2023

I’m having the same problem on PowerShell 7.3.2

image

1reaction
escservicescommented, Dec 8, 2020

@iSazonov Updated

Read more comments on GitHub >

github_iconTop Results From Across the Web

Powershell invoke-webrequest not working
I want to use this script with PRTG Network Monitor to ensure that a web server is up and running properly. Currently, the...
Read more >
Invoke-WebRequest - PowerShell
The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of...
Read more >
Not so simple invoke-webrequest : r/PowerShell
If your going to query a JSON API, then use "Invoke-RestMethod". It helps with the parsing. Clear-Host $url = 'http://data.phishtank.com/data/ ...
Read more >
PowerShell Invoke-WebRequest not returning data from ...
It appears that the INVOKE-WebRequest is not getting any data back no matter what type of variable is used? Is there any other...
Read more >
PowerShell v5 vs. PowerShell v7—Which to use and when
Let's differentiate Windows PowerShell v5.1 from PowerShell v7 and iron out any potential difficulties. Contents. PowerShell 5.1—Windows ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found