PoshCode Logo PowerShell Code Repository

HttpRest (modification of post by view diff)
View followups from Joel Bennett | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/691"></script>download | new post

An initial implementation of some Http REST cmdlets, as a series of script functions (usable as a script module, just save as a .psm1)

Documentation on this post on HuddledMasses

  1. ## Http Rest
  2. ####################################################################################################
  3. ## The first implementation of the HttpRest module, as a bunch of script functions
  4. ## Based on the REST api from MindTouch's Dream SDK
  5. ##
  6. ## INSTALL:
  7. ## You need log4net.dll mindtouch.core.dll mindtouch.dream.dll and SgmlReaderDll.dll from the SDK
  8. ## Download DREAM from http`://sourceforge.net/project/showfiles.php?group_id=173074
  9. ## Unpack it, and you can find these dlls in the "dist" folder.
  10. ## Make sure to put them in the folder with the module.
  11. ##
  12. ## For documentation of Dream:  http`://wiki.developer.mindtouch.com/Dream
  13. ####################################################################################################
  14. ## Usage:
  15. ##   function Get-Google {
  16. ##     Invoke-Http GET http`://www.google.com/search @{q=$args} |
  17. ##       Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText
  18. ##   }
  19. ##   #########################################################################
  20. ##   function Get-WebFile($url,$cred) {
  21. ##     Invoke-Http GET $url -auth $cred | Receive-Http File
  22. ##   }
  23. ##   #########################################################################
  24. ##   function Send-Paste {
  25. ##   PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file)
  26. ##   PROCESS {
  27. ##     if($_){[IO.FileInfo]$file=$_}
  28. ##
  29. ##     if($file.Exists) {
  30. ##       $ofs="`n"
  31. ##       $result = Invoke-Http POST $PastebinURI @{
  32. ##         format="posh"           # PowerShell
  33. ##         expiry="d"              # (d)ay or (m)onth or (f)orever
  34. ##         poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\")[-1])
  35. ##         code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter.
  36. ##         paste="Send"
  37. ##       } -Type FORM_URLENCODED -Wait
  38. ##       $xml = $result.AsDocument().ToXml()
  39. ##       write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href
  40. ##     } else { throw "File Not Found" }
  41. ##   }}
  42. ##
  43. ####################################################################################################
  44. if(!$PSScriptRoot){
  45.    Write-Debug $($MyInvocation.MyCommand | out-string)
  46.    $PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent)
  47. }
  48. #  Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)"
  49. #  Write-Debug "Invocation: $($MyInvocation.MyCommand)"
  50. #  Write-Debug "Invocation: $($MyInvocation)"
  51.  
  52. Write-Debug "PSScriptRoot: '$PSScriptRoot'"
  53.  
  54.  
  55. # This Module depends on MindTouch.Dream
  56. $null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\mindtouch.dream.dll" )
  57. # MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll)
  58. # This Module also depends on utility functions from System.Web
  59. $null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
  60.  
  61. ## Some utility functions are defined at the bottom
  62. [uri]$global:url = ""
  63. [System.Management.Automation.PSCredential]$global:HttpRestCredential = $null
  64.  
  65. function Get-DreamMessage($Content,$Type) {
  66.    if(!$Content) {
  67.       return [MindTouch.Dream.DreamMessage]::Ok()
  68.    }
  69.    if( $Content -is [System.Xml.XmlDocument]) {
  70.       return [MindTouch.Dream.DreamMessage]::Ok( $Content )
  71.    }
  72.    
  73.    if(Test-Path $Content -EA "SilentlyContinue") {
  74.       return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content)));
  75.    }
  76.    if($Type -is [String]) {
  77.       $Type = [MindTouch.Dream.MimeType]::$Type
  78.    }
  79.    if($Type -is [MindTouch.Dream.DreamMessage]) {
  80.       return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content )
  81.    } else {  
  82.       return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content )
  83.    }
  84. }
  85.  
  86. function Get-DreamPlug {
  87.    PARAM ( $Url, [hashtable]$With )
  88.    if($Url -is [array]) {
  89.       if($Url[0] -is [hashtable]) {
  90.          $plug = [MindTouch.Dream.Plug]::New($global:url)
  91.          foreach($param in $url.GetEnumerator()) {
  92.             if($param.Value) {
  93.                $plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)")
  94.             } else {
  95.                $plug = $plug.At($param.Key)
  96.             }
  97.          }
  98.       } else {
  99.          [URI]$uri = Join-Url $global:url $url
  100.          $plug = [MindTouch.Dream.Plug]::New($uri)
  101.       }
  102.    } elseif($url -is [string]) {
  103.       [URI]$uri = $url
  104.       if(!$uri.IsAbsoluteUri) {
  105.          $uri = Join-Url $global:url $url
  106.       }
  107.       $plug = [MindTouch.Dream.Plug]::New($uri)
  108.    } else {
  109.       $plug = [MindTouch.Dream.Plug]::New($global:url)
  110.    }
  111.    if($with) { foreach($param in $with.GetEnumerator()) {
  112.       if($param.Value) {
  113.          $plug = $plug.With($param.Key,$param.Value)
  114.       }
  115.    } }
  116.    return $plug
  117. }
  118.  
  119. #CMDLET Receive-Http {
  120. Function Receive-Http {
  121. PARAM(
  122.    #  [Parameter(Position=1, Mandatory=$false)]
  123.    #  [ValidateSet("Xml", "File", "Text","Bytes")]
  124.    #  [Alias("As")]
  125.    $Output = "Xml"
  126. ,
  127.    #  [Parameter(Position=2, Mandatory=$false)]
  128.    [string]$Path
  129. ,
  130.    #  [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")]
  131.    #  [Alias("IO")]
  132.    #  [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]
  133.    $InputObject
  134. #,
  135.    #  [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")]
  136.    #  [MindTouch.Dream.DreamMessage]
  137.    #  $response
  138. )
  139. BEGIN {
  140.    if($InputObject) {
  141.       Write-Output $inputObject | Receive-Http $Output $Path
  142.    } # else they'd better pass it in on the pipeline ...
  143. }
  144. PROCESS {
  145.    $response = $null
  146.    if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) {
  147.       $response = $_.Wait()
  148.    } elseif($_ -is [MindTouch.Dream.DreamMessage]) {
  149.       $response = $_
  150.    } elseif($_) {
  151.       throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects"
  152.    }
  153.    
  154.    if($response) {
  155.       Write-Debug $($response | Out-String)
  156.       if(!$response.IsSuccessful) {
  157.          Write-Error $($response | Out-String)
  158.          Write-Verbose $response.AsText()
  159.          throw "ERROR: '$($response.Status)' Response Status."
  160.       } else {  
  161.          switch($Output) {
  162.             "File" {
  163.                ## Joel's magic filename guesser ...
  164.                if(!$Path) {
  165.                   [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value
  166.                   $Path = $fileName.trim("\/""'")
  167.                   if(!$Path) {
  168.                      $fileName = $response.ResponseUri.Segments[-1]
  169.                      $Path = $fileName.trim("\/")
  170.                      if(!([IO.FileInfo]$Path).Extension) {
  171.                         $Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1]
  172.                      }
  173.                   }
  174.                }
  175.                
  176.                $File = Get-FileName $Path
  177.                [StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File )
  178.                Get-ChildItem $File
  179.             }
  180.             "XDoc" {
  181.                if($Path) {
  182.                   $response.AsDocument()[$Path]
  183.                } else {
  184.                   $response.AsDocument()#.ToXml()
  185.                }
  186.             }
  187.             "Xml" {
  188.                if($Path) {
  189.                   $response.AsDocument().ToXml().SelectNodes($Path)
  190.                } else {
  191.                   $response.AsDocument().ToXml()
  192.                }
  193.             }
  194.             "Text" {
  195.                if($Path) {
  196.                   $response.AsDocument()[$Path] | % { $_.AsText }
  197.                } else {
  198.                   $response.AsText()
  199.                }
  200.             }
  201.             "Bytes" {
  202.                $response.AsBytes()
  203.             }
  204.          }
  205.       }
  206.    }
  207. }
  208. }
  209. ## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  210. ## Nobody actually uses HEAD or OPTIONS, right?
  211. ## And nobody's even heard of TRACE or CONNECT ;)
  212.  
  213. # CMDLET Invoke-Http {
  214. Function Invoke-Http {
  215. PARAM(
  216.    # [Parameter(Position=0, Mandatory=$false)]
  217.    # [ValidateSet("Post", "Get", "Put", "Delete", "Head", "Options")] ## There are other verbs, but we need a list to make sure you don't screw up
  218.    [string]$Verb = "Get"
  219. ,
  220.    # [Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)]
  221.    # [string]
  222.    $Path
  223. ,
  224.    # [Parameter(Position=2, Mandatory=$false)]
  225.    [hashtable]$with
  226. ,
  227.    # [Parameter(Position=3, Mandatory=$false)]
  228.    $Content
  229. ,
  230.    $Type # Of Content
  231. ,
  232.    $authenticate
  233. ,
  234.    [switch]$waitForResponse
  235. )
  236. BEGIN {
  237.    $Verbs = "Post", "Get", "Put", "Delete", "Head", "Options"
  238.    if($Verbs -notcontains $Verb) {
  239.       Write-Warning "The specified verb '$Verb' is NOT one of the common verbs: $Verbs"
  240.    }
  241.  
  242.    if($Path) {
  243.       if($Content) {
  244.          Write-Output ($Path | Invoke-Http $Verb -With $With -Content $Content -Type $Type -Authenticate $authenticate -waitForResponse:$WaitForResponse)
  245.       } else {
  246.          Write-Output ($Path | Invoke-Http $Verb -With $With -Type $Type-Authenticate $authenticate -waitForResponse:$WaitForResponse)
  247.       }
  248.    } # else they'd better pass it in on the pipeline ...
  249. }
  250. PROCESS {
  251.    if($_) {
  252.       $Path = $_
  253.      
  254.       $plug = Get-DreamPlug $Path $With
  255.       Write-Verbose "Content Type: $Type"
  256.       Write-Verbose "Content: $Content"
  257.       ## Special Handling for FORM_URLENCODED
  258.       if($Type -like "Form*" -and !$Content) {
  259.          $dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri )
  260.          $Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath )
  261.          Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)"
  262.       } else {
  263.          $dream = Get-DreamMessage $Content $Type
  264.       }
  265.      
  266.       if(!$plug -or !$dream) {
  267.          throw "Can't come up with a request!"
  268.       }
  269.      
  270.       Write-Verbose $( $dream | Out-String )
  271.      
  272.       if($authenticate){
  273.             Write-Verbose "AUTHENTICATE AS $($authenticate.UserName)"
  274.          if($authenticate -is [System.Management.Automation.PSCredential]) {
  275.             Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
  276.             $plug = $plug.WithCredentials($authenticate.UserName, ($authenticate.GetNetworkCredential().Password))
  277.          } elseif($authenticate -is [System.Net.NetworkCredential]) {
  278.             Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
  279.             $plug = $plug.WithCredentials($authenticate.UserName, $authenticate.Password)
  280.          } else {
  281.             Get-HttpCredential
  282.             Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
  283.             $plug = $plug.WithCredentials($global:HttpRestCredential.UserName, $global:HttpRestCredential.Password)
  284.          }
  285.       }
  286.      
  287.       Write-Verbose $plug.Uri
  288.      
  289.       ## DEBUG:
  290.       Write-Debug "URI: $($Plug.Uri)"
  291.       Write-Debug "Verb: $($Verb.ToUpper())"
  292.       Write-Debug $($dream | Out-String)
  293.      
  294.       $result = $plug.InvokeAsync( $Verb.ToUpper(),  $dream )
  295.      
  296.       Write-Debug $($result | Out-String)
  297.       #  if($DebugPreference -eq "Continue") {
  298.       #     Write-Debug $($result.Wait() | Out-String)
  299.       #  }
  300.      
  301.       if($waitForResponse) {
  302.          $result = $result.Wait()
  303.       }
  304.      
  305.      
  306.       write-output $result
  307.    
  308.       trap [MindTouch.Dream.DreamResponseException] {
  309.          Write-Error @"
  310. TRAPPED DreamResponseException
  311.      
  312. $($_.Exception.Response | Out-String)
  313.  
  314. $($_.Exception.Response.Headers | Out-String)
  315. "@
  316.          break;
  317.       }
  318.    }
  319. }
  320. }
  321.  
  322. # function Get-Http { return Invoke-Http "GET" @args }
  323. # function New-Http { return Invoke-Http "PUT" @args }
  324. # function Update-Http { return Invoke-Http "POST" @args }
  325. # function Remove-Http { return Invoke-Http "DELETE" @args }
  326. # new-alias Set-Http Update-Http
  327. # new-alias Put-Http New-Http
  328. # new-alias Post-Http Update-Http
  329. # new-alias Delete-Http Remove-Http
  330.  
  331. function Set-HttpDefaultUrl {
  332. PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
  333.    $global:url = $baseUri
  334. }
  335.  
  336. function Set-HttpCredential {
  337.    param($Credential=$(Get-CredentialBetter -Title   "Http Authentication Request - $($global:url.Host)" `
  338.                                       -Message "Your login for $($global:url.Host)" `
  339.                                       -Domain  $($global:url.Host)) )
  340.    if($Credential -is [System.Management.Automation.PSCredential]) {
  341.       $global:HttpRestCredential = $Credential
  342.    } elseif($Credential -is [System.Net.NetworkCredential]) {
  343.       $global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password)
  344.    }
  345. }
  346.  
  347. function Get-HttpCredential([switch]$Secure) {
  348.    if(!$global:url) { Set-HttpDefaultUrl }
  349.    if(!$global:HttpRestCredential) { Set-HttpCredential }
  350.    if(!$Secure) {
  351.       return $global:HttpRestCredential.GetNetworkCredential();
  352.    } else {
  353.       return $global:HttpRestCredential
  354.    }
  355. }
  356.  
  357. # function Authenticate-Http {
  358. # PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential))
  359. #   $plug = [MindTouch.Dream.Plug]::New( $global:url )
  360. #   $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get()
  361. # }
  362.  
  363.  
  364. function Encode-Twice {
  365.    param([string]$text)
  366.    return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
  367. }
  368.  
  369. function Join-Url ( [uri]$baseUri=$global:url ) {
  370.    $ofs="/";$BaseUrl = ""
  371.    if($BaseUri -and $baseUri.AbsoluteUri) {
  372.       $BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/"
  373.    }
  374.    return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))"
  375. }
  376.  
  377. function ConvertTo-SecureString {
  378. Param([string]$input)
  379.    $result = new-object System.Security.SecureString
  380.  
  381.    foreach($c in $input.ToCharArray()) {
  382.       $result.AppendChar($c)
  383.    }
  384.    $result.MakeReadOnly()
  385.    return $result
  386. }
  387.  
  388. ## Unit-Test Get-FileName  ## Should return TRUE
  389. ##   (Get-FileName C:\Windows\System32\Notepad.exe)               -eq "C:\Windows\System32\Notepad.exe"   -and
  390. ##   (Get-FileName C:\Windows\Notepad.exe C:\Windows\System32\)   -eq "C:\Windows\System32\Notepad.exe"   -and
  391. ##   (Get-FileName WaitFor.exe C:\Windows\System32\WaitForIt.exe) -eq "C:\Windows\System32\WaitForIt.exe" -and
  392. ##   (Get-FileName -Path C:\Windows\System32\WaitForIt.exe)       -eq "C:\Windows\System32\WaitForIt.exe"      
  393. function Get-FileName {
  394.    param($fileName=$([IO.Path]::GetRandomFileName()), $path)
  395.    $fileName = $fileName.trim("\/""'")
  396.    ## if the $Path has a file name, and it's folder exists:
  397.    if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) {
  398.       $path
  399.    ## if the $Path is just a folder (and it exists)
  400.    } elseif($Path -and (Test-Path $path -Type Container)) {
  401.       $fileName = Split-Path $fileName -leaf
  402.       Join-Path $path $fileName
  403.    ## If there's no valid $Path, and the $FileName has a folder...
  404.    } elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
  405.       $fileName
  406.    } else {
  407.       Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf)
  408.    }
  409. }
  410.  
  411. function Get-UtcTime {
  412.    Param($Format="yyyyMMddhhmmss")
  413.    [DateTime]::Now.ToUniversalTime().ToString($Format)
  414. }
  415.  
  416. ## Get-CredentialBetter
  417. ## An improvement over the default cmdlet which has no options ...
  418. ###################################################################################################
  419. ## History
  420. ## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
  421. ## v 1.1 Add -Console switch and set registry values accordingly (ouch)
  422. ## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
  423. ###################################################################################################
  424. function Get-CredentialBetter{
  425. PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console)
  426.    $ShellIdKey = "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds"
  427.    ## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
  428.    $cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
  429.    ## Compare to $True, because by default it's $null ...
  430.    $cp = $cp.ConsolePrompting -eq $True
  431.  
  432.    if($Console -and !$cp) {
  433.       Set-ItemProperty $ShellIdKey ConsolePrompting $True
  434.    } elseif(!$Console -and $Console.IsPresent -and $cp) {
  435.       Set-ItemProperty $ShellIdKey ConsolePrompting $False
  436.    }
  437.  
  438.    ## Now call the Host.UI method ... if they don't have one, we'll die, yay.
  439.    $Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default")
  440.  
  441.    ## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
  442.    Set-ItemProperty $ShellIdKey ConsolePrompting $cp
  443. }
  444.  
  445.  
  446. # Export-ModuleMember Invoke-Http, Receive-Http, Set-HttpCredential, Set-HttpDefaultUrl

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me