Saturday, June 02, 2007 3:51 PM
Xaegr
Get-WwwContent
One of functions that i use very often is Get-WwwString. All what it does - downloads page from web and returns it in string. It is like unix command wget $url -O -
.Net have WebClient objects for doing things like this, so you just need to wrap it into function easy to use in PowerShell.
function Get-WwwContent ([string]$url, [string]$Encoding="utf-8"){
$wc = new-object System.Net.WebClient
$wc.Encoding = [System.Text.Encoding]::GetEncoding($Encoding)
$wc.DownloadString($url) }
You can just copy it and paste to PowerShell window, or place it in your profile. Also (and i prefer this way myself) you can add it to separate .ps1 file, and preload it in your profile. For example if you add it to c:\powershell\functions.ps1 and then add following line to your profile:
. c:\powershell\functions.ps1
This will load all functions contained in this file to PowerShell every time when it starts.
You can determine your profile location by looking in $profile variable:
PS> $profile
C:\Documents and Settings\User1\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
This file and folder doesnt exists by default, so you might need to create it:
PS> New-Item -ItemType file -Path $PROFILE -Force
and then edit it with notepad for example:
PS> notepad $profile
Lets return to Get-WwwString. When this function is added to PowerShell, you can use it to get content of webpages:
$googlePage = Get-WwwContent "http://www.google.com"
You can also specify optional parameter encoding (by default it is utf-8, but you can change this default value in function body if you want):
Get-WwwString "http://ya.ru" "windows-1251"