[NoBrainer] PowerShell Currency Converter

Today another NoBrainer how you can use PowerShell to do some currency conversions on the fly. The example shown here uses the OANDA(R) currency converter (Note: please read the terms of use if you are entitled to use the API or the web site in a programmatic way.)

Param (
  [Parameter(Mandatory = $true, Position = 0)]
  [string] $From
  ,
  [Parameter(Mandatory = $true, Position = 1)]
  [string] $To
  ,
  [Parameter(Mandatory = $false, Position = 2)]
  [Alias("Amount")]
  [double] $Value = 1
  ,
  [Parameter(Mandatory = $false, Position = 3)]
  [Alias("When")]
  [DateTime] $Date = [datetime]::Now
) # Param

$UrlTemplate = 'http://www.oanda.com/currency/converter/update?
  base_currency_0={0}&quote_currency={1}&end_date={2}&
  view=details&id=1&action=C&';
[Uri] $Url = $UrlTemplate -f $From, $To, $Date.ToString('yyyy-MM-dd');
$r = Invoke-RestMethod -Uri $Url;
if($PSBoundParameters.ContainsKey('Value')) {
  ($r.data.bid_ask_data | gm -Type Properties).Name |
    % { $r.data.bid_ask_data.$_ *= $Value; };
  for($c = 0; $c -lt $r.data.chart_data.Count; $c++)
    { $r.data.chart_data[$c][-1] *= $Value };
} # if
$Currency = [Ordered] @{};
($r.data.bid_ask_data | gm -Type Properties).Name |
  % { $Currency.Add($_, $r.data.bid_ask_data.$_); };
for($c = 0; $c -lt $r.data.chart_data.Count; $c++) {
  $dt = New-Object Datetime($r.data.chart_data[$c][0],
    $r.data.chart_data[$c][1], $r.data.chart_data[$c][2]);
  $Currency.Add($dt.ToString('yyyy-MM-dd'),
    $r.data.chart_data[$c][-1]);
} # for
return $Currency;

See Gist at https://gist.github.com/dfch/d5990fdb391fe1b84b76

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: