Many times you need to do a quick test that a web site or program works, or you want to download a web page within a script; in unix/linux, you'd probably use curl or wget ; Powershell (as of 3.0) has invoke-webrequest , which does a similar function.
Although it has many other options, the most basic invocation just takes a URL and it returns the 'output' of that request, as an object containing several fields; the Content field contains the actual information returned (the web page), so you can use something like this:
(Invoke-WebRequest http://okaram.com).Content.length
to find out its length, and could use String.Contains and such to verify that it returns the info you expected (so you could script a simpletest for your web app).
Other useful parameters include -OutFile to save the page to a file, and -UseDefaultCredentials to have the request use your windows credentials, in an intranet.
Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts
Saturday, November 2, 2013
Saturday, October 26, 2013
Powershell: Array2Object function
I've been using Powershell a lot recently (I'll be blogging a lot more about it soon); sometimes, you get an array and it is convenient to transform it into an object (so we can apply select and similar operators to it); objects in powershell can be created with the New-Object cmdlet, and we pass it the kind of object; the basic powershell object is of type psobject, and we can use Add-Member to add a field to it (powershell objects, like in most scripting languages, can have fields added dynamically to them)
The following function will create an object, given an array ; the object have fields f1,f2 ... corresponding to the array elements 0,1,...
function array2Object($arr)
{
$obj=New-Object psobject
$fn=0;
foreach($field in $arr) {
++$fn;
Add-Member -InputObject $obj -MemberType NoteProperty -Name "f$fn" -value $field
}
return $obj
}
The following function will create an object, given an array ; the object have fields f1,f2 ... corresponding to the array elements 0,1,...
function array2Object($arr)
{
$obj=New-Object psobject
$fn=0;
foreach($field in $arr) {
++$fn;
Add-Member -InputObject $obj -MemberType NoteProperty -Name "f$fn" -value $field
}
return $obj
}
Subscribe to:
Posts (Atom)