Displays flex query results from Interactive Brokers.
  Displays flex query V3 results from Interactive Brokers.
 .Parameter Query
  Flex query ID of Interactive Brokers.
 .Parameter Token
  Your flex web service token in Interactive Brokers.
   # Display flex query result, token is store in $Env:ibtoken.
   Get-IbReport -Query <Flex Query ID>
   # Display flex query result, specific token parameter.
   Get-IbReport -Query <Flex Query ID> -Token <Token>
   Online version:

function Get-IbReport {

  if ($token -ne $true) {

    if ((Test-Path "$env:appdata\Microsoft\Windows\PowerShell\IbToken.txt") -ne $true) {
      Write-Host "Please run 'Get-IbReport -Token' to provide Interactive Brokers token (Missing)" -ForegroundColor White -BackgroundColor Red
    if ($query -eq '') {
      Write-Host "Please run 'Get-IbReport -Query <<YOUR QUERY ID>>' to provide Interactive Brokers query ID (Missing)" -ForegroundColor White -BackgroundColor Red
    else {
      ## Define variables
      $ib_token = Get-Content "$env:appdata\Microsoft\Windows\PowerShell\IbToken.txt"
      $ib_version = 3
      $init_url = ""
      $getdata_url = ""

      #Authenticate to server
      $Body = @{
        t = $ib_token
        q = $query
        v = $ib_version
      $response = Invoke-WebRequest $init_url -Body $Body -Method 'POST'
      [xml]$ib_ref = $response.Content

      # Display IB Response Code
      # $ib_ref.FlexStatementResponse.ReferenceCode

      #Retrieve statement data
      $Body = @{
        q = $ib_ref.FlexStatementResponse.ReferenceCode
        t = $ib_token
        v = $ib_version
      $response = Invoke-WebRequest $getdata_url -Body $Body -Method 'POST'
      [xml]$xml = $response.Content

      if ($xml.FlexQueryResponse.type -eq "TCF") {
        $result = $xml.FlexQueryResponse.FlexStatements.FlexStatement.TradeConfirms.TradeConfirm

      if ($xml.FlexQueryResponse.type -eq "AF") {
        $result = $xml.FlexQueryResponse.FlexStatements.FlexStatement.ChangeInDividendAccruals.ChangeInDividendAccrual

      #Print result
      return $result
  else {
    Read-Host -Prompt "`nPlease provide token" | Out-File $env:appdata\Microsoft\Windows\PowerShell\IbToken.txt -Force
    Write-Host "`nYou can now run this with -Query to get report information" -ForegroundColor Green
    Write-Host "If you need to change the token, please run 'Get-IbReport -token' again`n" -ForegroundColor Green

Export-ModuleMember -Function Get-IbReport