Search code examples
powershellstockquotes

How to use PowerShell to query stock prices


I don't really have a problem, I'm trying to find a better way to get the current price of a stock using PowerShell Invoke-WebRequest. This is what I'm doing today:

Function Get-StockQuote($Uri) {
    
    $r = Invoke-WebRequest -Uri $Uri -UseBasicParsing
    
    #rip out the current market value in spectacularly unimpressive style
    $rc = $r.Content
    $trimRc = $rc.Substring( $rc.IndexOf('data-last-price="'), 25)
    $rip = $trimRc.Substring($TrimRc.IndexOf('"') + 1, $TrimRc.Length - $TrimRc.IndexOf('"') - 1)
    $value = $rip.Substring(0, $rip.IndexOf('"'))

    return [double]$value

}

$uri = 'https://www.google.com/finance/quote/MSFT:NASDAQ'
Get-StockQuote $uri

I get what I need but it is unreliable and it's just a sloppy way to do this. I'm looking for a more efficient solution to what feels like a fairly easy thing to do


Solution

  • A regex might be useful here instead of substring handling. I am not sure why you say that it is "unreliable".

    Function Get-StockQuote($Uri) {
        $r = Invoke-WebRequest -Uri $Uri -UseBasicParsing
        if ($r.Content -match 'data-last-price="([0-9\.]*)') {
            $value = [double]$Matches[1]
        } else {
            Write-Error -Message 'Price not found'
            $value = [double]0.0
        }
    
        return [double]$value
    }
    
    $uri = 'https://www.google.com/finance/quote/MSFT:NASDAQ'
    Get-StockQuote $uri