PoshCode Logo PowerShell Code Repository

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

Continued reworking in PowerShell 2.0 with parameter sets.

OLD documentation on this post on HuddledMasses

  1. #requires -version 2.0
  2. ## HttpRest module
  3. ####################################################################################################
  4. ## Initial stages of changing HttpRest into a v2-only module
  5. ## Based on the REST api from MindTouch's Dream SDK
  6. ##
  7. ## INSTALL:
  8. ## You need mindtouch.dream.dll (mindtouch.core.dll, SgmlReaderDll.dll, log4net.dll) from the SDK
  9. ## Download DREAM from http`://sourceforge.net/project/showfiles.php?group_id=173074
  10. ## Unpack it, and you can find these dlls in the "dist" folder.
  11. ## Make sure to put them in the folder with this script module.
  12. ##
  13. ## For documentation of Dream:  http`://wiki.developer.mindtouch.com/Dream
  14. ####################################################################################################
  15. ## Version History
  16. ## 1.0   First Release
  17. ## 1.0.1 Added Get-WebPageContent
  18. ## 1.0.2 Bug fix for Invoke-Http credential issues
  19. ## 1.1.0 First release of a PowerShell 2.0 (CTP3/Windows7) version....
  20. ## 1.1.1 Added Get-WebPageText and Get-Webfile ... cleaned up options
  21. ####################################################################################################
  22. ## Usage:
  23. ##   function Get-Google {
  24. ##     Invoke-Http GET http`://www.google.com/search @{q=$args} |
  25. ##       Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText
  26. ##   }
  27. ##   #########################################################################
  28. ##   function Get-WebFile($url,$cred) {
  29. ##     Invoke-Http GET $url -auth $cred | Receive-Http File
  30. ##   }
  31. ##   #########################################################################
  32. ##   function Send-Paste {
  33. ##   PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file)
  34. ##   PROCESS {
  35. ##     if($_){[IO.FileInfo]$file=$_}
  36. ##
  37. ##     if($file.Exists) {
  38. ##       $ofs="`n"
  39. ##       $result = Invoke-Http POST $PastebinURI @{
  40. ##         format="posh"           # PowerShell
  41. ##         expiry="d"              # (d)ay or (m)onth or (f)orever
  42. ##         poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\")[-1])
  43. ##         code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter.
  44. ##         paste="Send"
  45. ##       } -Type FORM_URLENCODED -Wait
  46. ##       $xml = $result.AsDocument().ToXml()
  47. ##       write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href
  48. ##     } else { throw "File Not Found" }
  49. ##   }}
  50. ##
  51. ####################################################################################################
  52. if(!$PSScriptRoot){
  53.    Write-Debug $($MyInvocation.MyCommand | out-string)
  54.    $PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent)
  55. }
  56. #  Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)"
  57. #  Write-Debug "Invocation: $($MyInvocation.MyCommand)"
  58. #  Write-Debug "Invocation: $($MyInvocation)"
  59.  
  60. Write-Debug "PSScriptRoot: '$PSScriptRoot'"
  61.  
  62.  
  63. # This Module depends on MindTouch.Dream
  64. $null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\mindtouch.dream.dll" )
  65. # MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll)
  66. # This Module also depends on utility functions from System.Web
  67. $null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
  68.  
  69. ## Some utility functions are defined at the bottom
  70. [uri]$global:url = ""
  71. [System.Management.Automation.PSCredential]$global:HttpRestCredential = $null
  72.  
  73. function Get-DreamMessage($Content,$Type) {
  74.    Write-Verbose "Content: $(if($Content){$Content.GetType()}else{"null"}) $($Content.Length) and Type: $(if($Type){$Type.GetType()}else{"null"})"
  75.    if(!$Content) {
  76.       Write-Verbose "No Content"
  77.       return [MindTouch.Dream.DreamMessage]::Ok()
  78.    }
  79.    if( $Content -is [System.Xml.XmlDocument]) {
  80.       Write-Verbose "Xml Content"
  81.       return [MindTouch.Dream.DreamMessage]::Ok( $Content )
  82.    }
  83.    
  84.    if(Test-Path $Content -EA "SilentlyContinue") {
  85.       Write-Verbose "File Content"
  86.       return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content)));
  87.    }
  88.    if($Type -is [String]) {
  89.       Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
  90.       $Type = [MindTouch.Dream.MimeType]::$Type
  91.    }
  92.    if($Type -is [MindTouch.Dream.DreamMessage]) {
  93.       Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
  94.       return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content )
  95.    } else {  
  96.       Write-Verbose "Unspecified string content"
  97.       return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content )
  98.    }
  99. }
  100.  
  101. function Get-DreamPlug {
  102.    [CmdletBinding()]
  103.    PARAM ( $Url, [hashtable]$With )
  104.    if($Url -is [array]) {
  105.       Write-Verbose "URL is an array of parts"
  106.       if($Url[0] -is [hashtable]) {
  107.          Write-Verbose "URL is an array of hashtable parts"
  108.          $plug = [MindTouch.Dream.Plug]::New($global:url)
  109.          foreach($param in $url.GetEnumerator()) {
  110.             if($param.Value) {
  111.                $plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)")
  112.             } else {
  113.                $plug = $plug.At($param.Key)
  114.             }
  115.          }
  116.       }
  117.       else
  118.       {
  119.          [URI]$uri = Join-Url $global:url $url
  120.          $plug = [MindTouch.Dream.Plug]::New($uri)
  121.       }
  122.    }
  123.    elseif($url -is [string])
  124.    {
  125.       Write-Verbose "String URL"
  126.       trap { continue }
  127.       [URI]$uri = $url
  128.       if(!$uri.IsAbsoluteUri) {
  129.          $uri = Join-Url $global:url $url
  130.          Write-Verbose "Relative URL, appending to $($global:url) to get: $uri"
  131.       }
  132.       $plug = [MindTouch.Dream.Plug]::New($uri)
  133.    }
  134.    else {
  135.       Write-Verbose "No URL, using default $($global:url)"
  136.       $plug = [MindTouch.Dream.Plug]::New($global:url)
  137.    }
  138.    if($with) {
  139.       foreach($param in $with.GetEnumerator()) {
  140.          if($param.Value) {
  141.             $plug = $plug.With($param.Key,$param.Value)
  142.          }
  143.       }
  144.       Write-Verbose "Added 'with' params: $plug"
  145.    }
  146.    return $plug
  147. }
  148.  
  149. #CMDLET Receive-Http {
  150. Function Receive-Http {
  151. PARAM(
  152.    #  [Parameter(Position=1, Mandatory=$false)]
  153.    #  [ValidateSet("Xml", "File", "Text","Bytes")]
  154.    #  [Alias("As")]
  155.    $Output = "Xml"
  156. ,
  157.    #  [Parameter(Position=2, Mandatory=$false)]
  158.    [string]$Path
  159. ,
  160.    #  [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")]
  161.    #  [Alias("IO")]
  162.    #  [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]
  163.    $InputObject
  164. #,
  165.    #  [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")]
  166.    #  [MindTouch.Dream.DreamMessage]
  167.    #  $response
  168. )
  169. BEGIN {
  170.    if($InputObject) {
  171.       Write-Output $inputObject | Receive-Http $Output $Path
  172.    } # else they'd better pass it in on the pipeline ...
  173. }
  174. PROCESS {
  175.    $response = $null
  176.    if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) {
  177.       $response = $_.Wait()
  178.    } elseif($_ -is [MindTouch.Dream.DreamMessage]) {
  179.       $response = $_
  180.    } elseif($_) {
  181.       throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects"
  182.    }
  183.    
  184.    if($response) {
  185.       Write-Debug $($response | Out-String)
  186.       if(!$response.IsSuccessful) {
  187.          Write-Error $($response | Out-String)
  188.          Write-Verbose $response.AsText()
  189.          throw "ERROR: '$($response.Status)' Response Status."
  190.       } else {  
  191.          switch($Output) {
  192.             "File" {
  193.                ## Joel's magic filename guesser ...
  194.                if(!$Path) {
  195.                   [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value
  196.                   $Path = $fileName.trim("\/""'")
  197.                   if(!$Path){
  198.                      if($response.ResponseUri)  {
  199.                         $fileName = $response.ResponseUri.Segments[-1]
  200.                         $Path = $fileName.trim("\/")
  201.                         if(!([IO.FileInfo]$Path).Extension) {
  202.                            $Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1]
  203.                         }
  204.                      }
  205.                   }
  206.                }
  207.                if($Path) {
  208.                   $File = Get-FileName $Path
  209.                } else {
  210.                   $File = Get-FileName
  211.                }
  212.                $null = [StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File )
  213.                Get-ChildItem $File
  214.             }
  215.             "XDoc" {
  216.                if($Path) {
  217.                   $response.AsDocument()[$Path]
  218.                } else {
  219.                   $response.AsDocument()#.ToXml()
  220.                }
  221.             }
  222.             "Xml" {
  223.                if($Path) {
  224.                   $response.AsDocument().ToXml().SelectNodes($Path)
  225.                } else {
  226.                   $response.AsDocument().ToXml()
  227.                }
  228.             }
  229.             "Text" {
  230.                if($Path) {
  231.                   $response.AsDocument()[$Path] | % { $_.AsText }
  232.                } else {
  233.                   $response.AsText()
  234.                }
  235.             }
  236.             "Bytes" {
  237.                $response.AsBytes()
  238.             }
  239.          }
  240.       }
  241.    }
  242. }
  243. }
  244. ## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  245. ## Nobody actually uses HEAD or OPTIONS, right?
  246. ## And nobody's even heard of TRACE or CONNECT ;)
  247.  
  248. # CMDLET Invoke-Http {
  249. Function Invoke-Http {
  250. [CmdletBinding(DefaultParameterSetName="NoCredentials")]
  251. PARAM(
  252.    [Parameter(Position=0, Mandatory=$false)]
  253.    [ValidateSet("Post", "Get", "Put", "Delete", "Head", "Options")] ## There are other verbs, but we need a list to make sure you don't screw up
  254.    [string]$Verb = "Get"
  255. ,
  256.    [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)]
  257.    [string]
  258.    $Path
  259. ,
  260.    [Parameter(Position=2, Mandatory=$false)]
  261.    [hashtable]$with
  262. ,
  263.    [Parameter(Mandatory=$false)]
  264.    $Content
  265. ,
  266.    [Parameter(Mandatory=$false)]
  267.    $Cookies
  268. ,
  269.    [Parameter(Mandatory=$false)]
  270.    $Type # Of Content
  271. ,
  272.    [Parameter(ParameterSetName="UseDefaultCredentials")]
  273.    [switch]$authenticate
  274. ,
  275.    [Parameter(ParameterSetName="ManualCredentials")]
  276.    $credentials
  277. ,
  278.    [Parameter(Mandatory=$false)]
  279.    [switch]$Persistent  ## Note this ALSO causes WaitForResponse
  280. ,
  281.    [switch]$waitForResponse
  282. )
  283. PROCESS {
  284.       $plug = Get-DreamPlug $Path $With
  285.       Write-Verbose "Content Type: $Type"
  286.       Write-Verbose "Content: $Content"
  287.       ## Special Handling for FORM_URLENCODED
  288.       if($Type -like "Form*" -and !$Content) {
  289.          $dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri )
  290.          $Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath )
  291.          Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)"
  292.       } else {
  293.          $dream = Get-DreamMessage $Content $Type
  294.          Write-Verbose "Created Dream with Content: $($dream.Content)"
  295.       }
  296.      
  297.       if(!$plug -or !$dream) {
  298.          throw "Can't come up with a request!"
  299.       }
  300.      
  301.       if($Persistent -and $global:HttpRestCookies) {
  302.          $dream.Cookies.Add( $global:HttpRestCookies );
  303.       }
  304.       if($Cookies) {
  305.          $dream.Cookies.Add( $Cookies );
  306.       }
  307.      
  308.       Write-Verbose $("DREAM!",$dream | Out-String )
  309.      
  310.       if($authenticate -or $credentials){
  311.          if($credentials -is [System.Management.Automation.PSCredential]) {
  312.             Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
  313.             $plug = $plug.WithCredentials($credentials.GetNetworkCredential())
  314.          } elseif($credentials -is [System.Net.ICredentials]) {
  315.             Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
  316.             $plug = $plug.WithCredentials($credentials.GetNetworkCredential())
  317.          } else {
  318.             if($credentials) {
  319.                Write-Error "Credential must be a PSCredential or a System.Net.ICredentials"
  320.             }
  321.             $null = Get-HttpCredential  # Make sure they have global credentials
  322.             Write-Verbose "AUTHENTICATING AS $($global:HttpRestCredential.UserName)"
  323.             $plug = $plug.WithCredentials($global:HttpRestCredential.GetNetworkCredential())
  324.          }
  325.       }
  326.      
  327.       Write-Verbose $plug.Uri
  328.      
  329.       ## DEBUG:
  330.       Write-Debug "URI: $($Plug.Uri)"
  331.       Write-Debug "Verb: $($Verb.ToUpper())"
  332.       Write-Debug $($dream | Out-String)
  333.      
  334.       $result = $plug.InvokeAsync( $Verb.ToUpper(),  $dream )
  335.      
  336.       Write-Debug $($result | Out-String)
  337.       #  if($DebugPreference -eq "Continue") {
  338.       #     Write-Debug $($result.Wait() | Out-String)
  339.       #  }
  340.      
  341.       if($waitForResponse -or $Persistent) {
  342.          $result = $result.Wait()
  343.          $global:HttpRestCookies = $result.Cookies
  344.       }
  345.      
  346.       write-output $result
  347.    
  348.       trap [MindTouch.Dream.DreamResponseException] {
  349.          Write-Error @"
  350. TRAPPED DreamResponseException
  351.      
  352. $($_.Exception.Response | Out-String)
  353.  
  354. $($_.Exception.Response.Headers | Out-String)
  355. "@
  356.          break;
  357.       }
  358. }
  359. }
  360.  
  361.  
  362. function Get-WebPageContent {
  363. [CmdletBinding()]
  364. param(
  365.    [Parameter(Position=0,Mandatory=$true)]
  366.    [string]$url
  367. ,
  368.    [Parameter(Position=1,Mandatory=$false)]
  369.    [string]$xpath=""
  370. ,
  371.    [Parameter(Position=2,Mandatory=$false)]
  372.    [hashtable]$with=@{}
  373. ,
  374.    [Parameter(Mandatory=$false)]
  375.    [switch]$Persist
  376. ,
  377.    [Parameter(Mandatory=$false)]
  378.    [switch]$Authenticate
  379. )
  380. BEGIN { $out = "Text"; if($Xml) { $out="Xml" } }
  381. PROCESS {
  382.    invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http xml $xpath
  383. }
  384. }
  385.  
  386. function Get-WebPageText {
  387. [CmdletBinding()]
  388. param(
  389.    [Parameter(Position=0,Mandatory=$true)]
  390.    [string]$url
  391. ,
  392.    [Parameter(Position=1,Mandatory=$false)]
  393.    [string]$xpath=""
  394. ,
  395.    [Parameter(Position=2,Mandatory=$false)]
  396.    [hashtable]$with=@{}
  397. ,
  398.    [Parameter(Mandatory=$false)]
  399.    [switch]$Persist
  400. ,
  401.    [Parameter(Mandatory=$false)]
  402.    [switch]$Authenticate
  403. )
  404. BEGIN { $out = "Text"; if($Xml) { $out="Xml" } }
  405. PROCESS {
  406.    invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http text $xpath
  407. }
  408. }
  409.  
  410. function Get-WebFile {
  411. [CmdletBinding()]
  412. param(
  413.    [Parameter(Position=0,Mandatory=$true)]
  414.    [string]$url
  415. ,
  416.    [Parameter(Position=1,Mandatory=$false)]
  417.    [string]$path=""
  418. ,
  419.    [Parameter(Position=2,Mandatory=$false)]
  420.    [hashtable]$with=@{}
  421. ,
  422.    [Parameter(Mandatory=$false)]
  423.    [switch]$Persist
  424. ,
  425.    [Parameter(Mandatory=$false)]
  426.    [switch]$Authenticate
  427. )
  428. PROCESS {
  429.    Invoke-Http GET $url $with -Authenticate:$Authenticate -Persist:$Persist | Receive-Http File $path
  430. }
  431. }
  432.  
  433.  
  434. new-alias gwpc Get-WebPageContent -EA "SilentlyContinue"
  435. new-alias http Invoke-Http        -EA "SilentlyContinue"
  436. new-alias rcv  Receive-Http       -EA "SilentlyContinue"
  437.  
  438.  
  439. # function Get-Http { return Invoke-Http "GET" @args }
  440. # function New-Http { return Invoke-Http "PUT" @args }
  441. # function Update-Http { return Invoke-Http "POST" @args }
  442. # function Remove-Http { return Invoke-Http "DELETE" @args }
  443. # new-alias Set-Http Update-Http
  444. # new-alias Put-Http New-Http
  445. # new-alias Post-Http Update-Http
  446. # new-alias Delete-Http Remove-Http
  447.  
  448. function Set-HttpDefaultUrl {
  449. PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
  450.    $global:url = $baseUri
  451. }
  452.  
  453. function Set-HttpCredential {
  454.    param($Credential=$(Get-CredentialBetter -Title   "Http Authentication Request - $($global:url.Host)" `
  455.                                       -Message "Your login for $($global:url.Host)" `
  456.                                       -Domain  $($global:url.Host)) )
  457.    if($Credential -is [System.Management.Automation.PSCredential]) {
  458.       $global:HttpRestCredential = $Credential
  459.    } elseif($Credential -is [System.Net.NetworkCredential]) {
  460.       $global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password)
  461.    }
  462. }
  463.  
  464. function Get-HttpCredential {
  465.    if(!$global:url) { Set-HttpDefaultUrl }
  466.    if(!$global:HttpRestCredential) { Set-HttpCredential }
  467.    if(!$Secure) {
  468.       return $global:HttpRestCredential.GetNetworkCredential();
  469.    } else {
  470.       return $global:HttpRestCredential
  471.    }
  472. }
  473.  
  474. # function Authenticate-Http {
  475. # PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential))
  476. #   $plug = [MindTouch.Dream.Plug]::New( $global:url )
  477. #   $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get()
  478. # }
  479.  
  480.  
  481. function ConvertTo-UrlDoubleEncode {
  482.    param([string]$text)
  483.    return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
  484. }
  485. New-Alias Encode-Twice ConvertTo-UrlDoubleEncode
  486.  
  487. function Join-Url ( [uri]$baseUri=$global:url ) {
  488.    $ofs="/";$BaseUrl = ""
  489.    if($BaseUri -and $baseUri.AbsoluteUri) {
  490.       $BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/"
  491.    }
  492.    return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))"
  493. }
  494.  
  495. function ConvertTo-SecureString {
  496. Param([string]$input)
  497.    $result = new-object System.Security.SecureString
  498.  
  499.    foreach($c in $input.ToCharArray()) {
  500.       $result.AppendChar($c)
  501.    }
  502.    $result.MakeReadOnly()
  503.    return $result
  504. }
  505.  
  506. ## Unit-Test Get-FileName  ## Should return TRUE
  507. ##   (Get-FileName C:\Windows\System32\Notepad.exe)               -eq "C:\Windows\System32\Notepad.exe"   -and
  508. ##   (Get-FileName C:\Windows\Notepad.exe C:\Windows\System32\)   -eq "C:\Windows\System32\Notepad.exe"   -and
  509. ##   (Get-FileName WaitFor.exe C:\Windows\System32\WaitForIt.exe) -eq "C:\Windows\System32\WaitForIt.exe" -and
  510. ##   (Get-FileName -Path C:\Windows\System32\WaitForIt.exe)       -eq "C:\Windows\System32\WaitForIt.exe"      
  511. function Get-FileName {
  512.    param($fileName=$([IO.Path]::GetRandomFileName()), $path)
  513.    $fileName = $fileName.trim("\/""'")
  514.    ## if the $Path has a file name, and it's folder exists:
  515.    if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) {
  516.       $path
  517.    ## if the $Path is just a folder (and it exists)
  518.    } elseif($Path -and (Test-Path $path -Type Container)) {
  519.       $fileName = Split-Path $fileName -leaf
  520.       Join-Path $path $fileName
  521.    ## If there's no valid $Path, and the $FileName has a folder...
  522.    } elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
  523.       $fileName
  524.    } else {
  525.       Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf)
  526.    }
  527. }
  528.  
  529. function Get-UtcTime {
  530.    Param($Format="yyyyMMddhhmmss")
  531.    [DateTime]::Now.ToUniversalTime().ToString($Format)
  532. }
  533.  
  534. ## Get-CredentialBetter
  535. ## An improvement over the default cmdlet which has no options ...
  536. ###################################################################################################
  537. ## History
  538. ## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
  539. ## v 1.1 Add -Console switch and set registry values accordingly (ouch)
  540. ## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
  541. ###################################################################################################
  542. function Get-CredentialBetter{
  543. PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console)
  544.    $ShellIdKey = "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds"
  545.    ## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
  546.    $cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
  547.    ## Compare to $True, because by default it's $null ...
  548.    $cp = $cp.ConsolePrompting -eq $True
  549.  
  550.    if($Console -and !$cp) {
  551.       Set-ItemProperty $ShellIdKey ConsolePrompting $True
  552.    } elseif(!$Console -and $Console.IsPresent -and $cp) {
  553.       Set-ItemProperty $ShellIdKey ConsolePrompting $False
  554.    }
  555.  
  556.    ## Now call the Host.UI method ... if they don't have one, we'll die, yay.
  557.    $Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default")
  558.  
  559.    ## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
  560.    Set-ItemProperty $ShellIdKey ConsolePrompting $cp -ea "SilentlyContinue"
  561. }
  562.  
  563. Export-ModuleMember -Function * -Alias *
  564. # Export-ModuleMember Invoke-Http, Receive-Http, Set-HttpCredential, Set-HttpDefaultUrl
  565. # SIG # Begin signature block
  566. # MIIIPgYJKoZIhvcNAQcCoIIILzCCCCsCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
  567. # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
  568. # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUQoaUUrGbT13oF6YhXlqqJ9qf
  569. # SqOgggVbMIIFVzCCBD+gAwIBAgIRAO2rPg5HUjL4ofGGpnMP2jwwDQYJKoZIhvcN
  570. # AQEFBQAwgZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2Fs
  571. # dCBMYWtlIENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8G
  572. # A1UECxMYaHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNF
  573. # UkZpcnN0LU9iamVjdDAeFw0wODEwMDYwMDAwMDBaFw0wOTEwMDYyMzU5NTlaMIHE
  574. # MQswCQYDVQQGEwJVUzEOMAwGA1UEEQwFMTQ2MjMxETAPBgNVBAgMCE5ldyBZb3Jr
  575. # MRIwEAYDVQQHDAlSb2NoZXN0ZXIxFDASBgNVBAkMC01TIDA4MDEtMTdBMRowGAYD
  576. # VQQJDBExMzUwIEplZmZlcnNvbiBSZDEaMBgGA1UECgwRWGVyb3ggQ29ycG9yYXRp
  577. # b24xFDASBgNVBAsMC1NFRURVIFRvb2xzMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
  578. # dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK50RXT2KUvECfWZ
  579. # weqeXzTCykPPRh9nC3Hzur/mmvkQHA8iinnSKX4j19C1/MV0rAEeCU1bF7Sgxvov
  580. # ORreM1Ye/wEqJLAUP/IGZI/qsmmwasGFGbnuevpA3WieNCr5cFGl8Y5Mx6ejaDFi
  581. # O0GT9EM6gOGZaEEMRbHZc4qXT7CrWScs4Yur5bBZsowaMk5JkvZgihhnN93QolEW
  582. # ObmtQZlbBDqLuoL9fUnIexlqqIrC/4h0K8VM26HvqhgGlQF2wf4t9xCHFJiX2F7D
  583. # B10lef5aXzyPVrvxxrRWyBtCQuL7xdXneRanJaYG3B3kclc+4/6dq9a+s/huXjmE
  584. # omumgGcCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
  585. # PMnYMB0GA1UdDgQWBBT5ITlG5CdiD+nI0uTqnXNGnd44QjAOBgNVHQ8BAf8EBAMC
  586. # B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
  587. # AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
  588. # ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
  589. # M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
  590. # LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
  591. # bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
  592. # CSqGSIb3DQEBBQUAA4IBAQAZxnV+BbJBohpy+wKs6U8hRiPUhDYaijzTyrZontf5
  593. # PEyBbhAkJFIWauIaq9eSQEJeErXO/zuO6+wY/azBzOTleMM9qdGWHFtfAw5WiIuC
  594. # 90TzDBSuP7LImZV5Pb6nxRbesDF2U7EM5sBzYSWAMfpBmYRz97EHPW5QNzpBLFJn
  595. # Dhb/M27rDYh7FVjy1+C5E3glIa0A0q+lcxEtFuUij4JId+oMcfpSgYJZvR1Kvkjd
  596. # GDAtWCzvALaNFd65kChbrOqcClOCacQRnP9N4DJl/RVNKZtcUcVAyTpvOlJBA5vG
  597. # OVcsJT4TnSMjPX6d5pXMwcE1oWCUWvK99W+N81DvBBuZMYICTTCCAkkCAQEwgasw
  598. # gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
  599. # IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
  600. # aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
  601. # LU9iamVjdAIRAO2rPg5HUjL4ofGGpnMP2jwwCQYFKw4DAhoFAKB4MBgGCisGAQQB
  602. # gjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYK
  603. # KwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFDt2csas
  604. # cPdhVfQXLYSciOvpftO/MA0GCSqGSIb3DQEBAQUABIIBAKFpe16JPkouVrUMZZQ1
  605. # 5oOiDnb/XVyBdvQw9DSEOi/g6lbdITlTo9RElg+yWO+w4+igiNYTpS3xyUZ00TI4
  606. # DxWToZuOYXr+a/LseWpg/T/HVGzYT94ZBhEIsz0jpnlwvKt4qcU/tYCDDf+1Yoqk
  607. # P62qr1pnpNEVDEtPWWzlS/iNZNk3SmcVaNg/FL7dLCXsyqyWAS72d3EIKH3CbaPG
  608. # raoxSWRGnsk+qOiAT3lD4luyCc6O+cUg3LwtPLghzYFpW16HCJrCmsNbtwqjnzX4
  609. # Uqs9jRvwirRD5NtABEFpYabxn+a0zUW+nI1Pca4d4CBEvbU4mpdgvStsoizaC+5W
  610. # 20k=
  611. # SIG # End signature block

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