3

Forgive my ignorance - I am trying to write a powershell cmdlet which takes user input and builds a query uri to an API (one mandatory, 3 opts) - I have kind of got the general idea that I need to use hash tables for dictionary of query strings and parameters.

I'm trying to build $baseurl + $querystring + '=' + $parameter + '&' + $querystring + '=' $value (if not null)

e.g. https://example.com/api?param1=value&param2=value

so far - and this is very rough, and completely not working:

            Function Get-commonURI{ #takes 4 params from user
                [CmdletBinding()]
                Param(
                    [Parameter(Mandatory=$true,
                                ValueFromPipeline=$true,
                                ValueFromPipelineByPropertyName=$true)]

                                [String[]]$value1

                                [Parameter(Mandatory=$false,
                                ValueFromPipeline=$true,
                                ValueFromPipelineByPropertyName=$true)]

                                [String[]]$value2,
                                [String[]]$value3,
                                [String[]]$value4 

                ) #end param 
            }
        #put the input into a paramter hash table with the query strings

        $Parameters = @{
            query = 'querysting1', 'querystring2', 'querystring3', 'querystring4'
            values = $value1,$value2.$value2, $value4
        }

        uri = https://example.com/api?

    $HttpValueCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)

    foreach ($Item in $Parameters.GetEnumerator()) {
#I want to append each query passed in on the cli

foreach ($Value in $Item.Value) {
      $ParameterName = $Item.value

      $HttpValueCollection.Add($ParameterName, $Value)}

$Request  = [System.UriBuilder]($Uri)
$Request.Query = $HttpValueCollection.ToString()

invoke-webrequest $Request.Uri

}

I have something like that written but it's not working - am I even on the right track here? - I'm sure this has been done a million times but don't even know what to google - something tells me I shouldn't set up the hash table with variables. thanks for looking.

2
  • Hi, your code does not run as-is, and is not well indented so it is hard to read and understand. Can you please try to fix it a bit? For example, I think the first closing curly bracket is misplaced because it ends the function declaration block. I'm afraid I'll break your logic if I try to change things. Also, if you want to take user input, you can try with: $userValue1 = Read-Host "enter first value" for instance.
    – sodawillow
    Jan 31, 2017 at 21:25
  • thanks sodawillow, I'm just trying to get an idea of how to build the query string using hash table - not really looking for code per se, I want to build it as a cmdlet so users can tab out the parameters rather than being prompted so get-commonURI -param1 value and get-commonURI -param1 value param2 value the cmdlet should build the correct uri
    – Sum1sAdmin
    Jan 31, 2017 at 22:07

2 Answers 2

17

I'm always a fan of not re-inventing the wheel:

$ub = new-object System.UriBuilder -argumentlist 'http', 'myhost.com', 80, 'mypath/query.aspx', '?param=value'
$ub.Uri.AbsoluteUri
>>>> http://myhost.com/mypath/query.aspx?param=value

Update:

This is a built-in .NET class which has numerous constructors. The one above accepts a protocol, host, port number, path and query string. It seems to handle an empty or null query string, so no need to handle this yourself. For info, the class' constructor can be seen here. In order to retrieve input from the user, you can use Read-Host, e.g.:

[String] $Local:strServer = '';
[String] $Local:strPath   = '';
[String] $Local:strQuery  = '';
[String] $Local:strUri    = '';

while ( $strServer -eq '' ) {
    $strServer = Read-Host -Prompt 'Please enter a server name';
    } #while
while ( $strPath -eq '' ) {
    $strPath   = Read-Host -Prompt 'Please enter a path';
    } #while

# Get query string and ensure it begins with a "?".
$strQuery  = Read-Host -Prompt 'Please enter a query string';
if ( ($strQuery -ne '') -and (! $strQuery.StartsWith('?')) ) { $strQuery = '?' + $strQuery; } 

try {
    $strUri = [System.UriBuilder]::new( 'http', $strServer, 80, $strPath, $strQuery );
    Write-Host -Object ( 'URI is {0}' -f $strUri );
    } #try
catch [System.ArgumentException] {
    # Something went wrong.
    } #catch
3
  • thanks Simon, can you elaborate on it a bit, especially with regard to user input and not appending the query string if the parameter is null. thanks.
    – Sum1sAdmin
    Jan 31, 2017 at 20:43
  • nice one thanks, on a Mac right now but will try this tomorrow and let you know, will accept the answer once I get it a try! thanks again.
    – Sum1sAdmin
    Jan 31, 2017 at 22:23
  • Method invocation failed because [System.UriBuilder] does not contain a method named 'new' That isn't how you construct .NET objects in PowerShell.
    – jpmc26
    Jan 24, 2018 at 2:11
0

In the end I wrote this as a cmdlet that takes pipeline input and can be invoked from other scripts - it can open the uri in a browser, save the xml as a document, or cast the document as an xml type object - which is very handy as you can then select the xml object properties (xml nodes, attributes) using dotted notation instead of xPath and Powershells intellisense uses tab completion so you can cycle thru the xml nodes on the command line or in the Powershell ISE.

I also use the powershell community extensions module https://pscx.codeplex.com/ for it's sensible join-string cmdlet.

Add-Type -AssemblyName System.Web
$authparam = '&auth='
$baseURI = 'https://example.com/restapi?'
$password = 'plaintextpassword'

Function Get-APICommon
{
    #takes 4 params and auth key
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $false,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [String[]]$param1,
        [String[]]$Param2,
        [String[]]$Param3,
        [String[]]$Param4

    ) #end param 

    Begin { }
    process
    {

        $Parameters = [ordered] @{
            Query1 = $Param1
            Query2 = $Param2
            Query3 = $Param3
            Query4 = $Param4
        }
        #This particular API needs to have query parameters separated by ':' and hashed as part of the authentication parameter i.e param1:param2:param3:param4:password
        $preauth = ($Parameters.GetEnumerator() | % { "$($_.Value)" }) -join ':'

        $prehash = Join-String $preauth, ':', $password
        $hash = $prehash | Get-Hash -Algorithm SHA1 -StringEncoding ascii


        foreach ($item in $Parameters.GetEnumerator())
        {

            if ($item.value -ne $null)
            {

                $query =[System.Web.HttpUtility]::ParseQueryString($uriBuilder.Query)
                $query[$item.key] = $item.Value

                $uriBuilder = [System.UriBuilder]::new($baseURI)
                $uriBuilder.Query = $query.ToString()
                $baseURI = $uriBuilder.ToString()
            }



        }

        $queryURI = Join-String $baseURI, $authparam, $hash
        Write-Host $queryURI


    $Resultfile = Join-String $($Parameters.Query1),'-Result.xml'

    $Resultxml = [xml](Invoke-WebRequest -Uri $queryURI | Select-Object -ExpandProperty content | Out-File $Resultfile)

    $Parameters.Clear()


        $Browser = new-object -com internetexplorer.application

        $Browser.navigate2("$queryURI")

        $Browser.visible = $true


    }


}

Example usage

get-APICommon -param1 querystring

or

get-APICommon -param1 queryvalue1 -param2 queryvalue2

example results

https://example.com/restapi?&query1=queryvalue&query2=queryvalue2&auth=JSJAUJQJALF09OLQLS34LLK

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.