Accessing RESTful web services is trivial for PowerShell: simply send your input data to a public web service, and receive the results.

Here are three PowerShell functions designed to each do a numeric conversion:

function Convert-InchToCentimeter
{
  param
  (
    [Parameter(Mandatory)]
    [Double]
    $Inch
  )
  [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  $url = 'https://ucum.nlm.nih.gov/ucum-service/v1/ucumtransform/{0}/from/%5Bin_i%5D/to/cm' -f $Inch
  $result = Invoke-RestMethod -Uri $url -UseBasicParsing 
  $result.UCUMWebServiceResponse.Response
}


function Convert-FootToMicrometer
{
  param
  (
    [Parameter(Mandatory)]
    [Double]
    $Foot
  )
  [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  $url = 'https://ucum.nlm.nih.gov/ucum-service/v1/ucumtransform/{0}/from/%5Bft_i%5D/to/um' -f $Foot
  $result = Invoke-RestMethod -Uri $url -UseBasicParsing 
  $result.UCUMWebServiceResponse.Response
}


function Convert-GramToOunce
{
  param
  (
    [Parameter(Mandatory)]
    [Double]
    $Gram
  )
  [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  $url = 'https://ucum.nlm.nih.gov/ucum-service/v1/ucumtransform/{0}/from/g/to/%5Boz_ap%5D' -f $Gram
  $result = Invoke-RestMethod -Uri $url -UseBasicParsing 
  $result.UCUMWebServiceResponse.Response
}

Provided you have Internet access, then doing conversions is as simple as a function call:

 
PS C:\> Convert-GramToOunce -Gram 230

SourceQuantity SourceUnit TargetUnit ResultQuantity
-------------- ---------- ---------- --------------
230.0          g          [oz_ap]    7.3946717   
 

The important points to keep in mind are:

  • You need to allow Tls12 to enable HTTPS connections (see code)
  • You need to follow the rules set forth by the web service, i.e. when it requires whole numbers, you cannot submit decimals

There are plenty more conversions available at https://ucum.nlm.nih.gov/ucum-service.html#conversion, so you can use the functions provided as a template to create more conversion functions.


Twitter This Tip! ReTweet this Tip!

Anonymous