Search code examples
powershellscriptblock

Invoking Restmethod URI in Powershell Scriptblock not working


There seems to be an issue with the Scriptblock which is causing it to not process and I think it maybe a simple syntax issue:

        function start-wait4 {
        $scroll = "/-\|/-\|"
        $idx = 0
        $job = Invoke-Command -ComputerName $env:ComputerName -ScriptBlock { Invoke-Expression (Invoke-RestMethod -Uri "https://webaddresswherecodeishosted") } -AsJob

        $origpos = $host.UI.RawUI.CursorPosition
        $origpos.Y += 1

        while (($job.State -eq "Running") -and ($job.State -ne "NotStarted")) {
            $host.UI.RawUI.CursorPosition = $origpos
            Write-Host $scroll[$idx] -NoNewline
            $idx++
            if ($idx -ge $scroll.Length) {
                $idx = 0
            }
            Start-Sleep -Milliseconds 100
        }
        # It's over - clear the activity indicator.
        $host.UI.RawUI.CursorPosition = $origpos
        Write-Host ' '
    }
    start-wait4

Start-wait4 should begin processing the remote script and display the spinning waiting symbol but is failing.


Solution

  • It was actually the InvokeCommand part that was the issue, needed to be changed to Start-Job:

          function start-wait4 {
            $scroll = "/-\|/-\|"
            $idx = 0
            $job = Start-Job -ScriptBlock { Invoke-Expression (Invoke-RestMethod -Uri "https://webaddresswithremotecode") } 
    
            $origpos = $host.UI.RawUI.CursorPosition
            $origpos.Y += 1
    
            while (($job.State -eq "Running") -and ($job.State -ne "NotStarted")) {
                $host.UI.RawUI.CursorPosition = $origpos
                Write-Host $scroll[$idx] -NoNewline
                $idx++
                if ($idx -ge $scroll.Length) {
                    $idx = 0
                }
                Start-Sleep -Milliseconds 100
            }
            # It's over - clear the activity indicator.
            $host.UI.RawUI.CursorPosition = $origpos
            Write-Host ' '
        }
        start-wait4