Search This Blog

Sunday, June 7, 2015

Getting a Web Page with PowerShell

This is a patern to get a webpage. I sometimes work in a network accessing the internet through a proxy, So there is included a block where proxy creds are used.

GetWebPage.ps1
#http://learn-powershell.net/2011/02/11/using-powershell-to-query-web-site-information/
#http://stackoverflow.com/questions/571429/powershell-web-requests-and-proxies

Begin {
    $user = $env:username
    $url = "https://hereisasite.net"
    #$url = "http://google.com"
    $pwd = Read-Host "Password?" -assecurestring
    $account = new-object System.Net.NetworkCredential($user,[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd)), "")

    #$proxyAddr = (get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').ProxyServer
    #$proxy = new-object System.Net.WebProxy
    #$proxy.Address = $proxyAddr
    #$proxy.credentials = $account
    #$proxy.useDefaultCredentials = $true

    $web = New-Object System.Net.WebClient
    $web.Credentials = $account
    #$web.proxy = $proxy

    $flag = $false
}
Process {
    While ($flag -eq $false) {
        Try {
            $webpage = $web.DownloadData($url)
            $str = [System.Text.Encoding]::ASCII.GetString($webpage)
            $flag = $true
        } Catch {
             Write-host -fore Red -nonewline "Access down... "
             $str = "Nothing to see here... "
             $flag = $true
        }
    }
}
End{
    Write-Host $str
}