title: How to avoid errors when casting null REST data to datetime
body: <p>I am using a REST API to pull invoice data, from an external company, into an Excel file using PowerShell. I can pull the data just fine using the Invoke-RestMethod. Although, when it pulls the datetime fields, it is in a format I do not prefer. To automate my job as much as possible, is there a way to cast the data to datetime. Keep in mind, not every field has data so there are null fields which cause the errors. I basically want to pull all data, if it has an ugly-formatted datetime, change it to the way I want to see it, or if it is empty, just continue on.</p>
  
  <p>I have tried [nullable[datetime]] (found it on google somewhere), but that throws other errors. I have tried using an 'IF' but that also generates in out set of syntax errors.</p>
  
  <pre><code>$out = Invoke-RestMethod -Uri $assetsURL
  #$out.Invoices | Export-Excel $outputcsv
  $out.Invoices |
      Select-Object * |
      ForEach-Object {
          $Properties = [ordered]@{
          InvoiceNumber = $_.InvoiceNumber
          DueDate = $_.DueDate #[datetime]::parseexact($_.DueDate, 'yyyy-MM-ddThh:mm:ss', $null).ToString('yyyy-MM-dd')
          Currency = $_.Currency
          TotalDue = $_.TotalDue
          PeriodFrom = $_.PeriodFrom #[datetime]::parseexact($_.PeriodFrom,'yyyy-MM-ddThh:mm:ss', $null).ToString('yyyy-MM-dd')
          PeriodTo = $_.PeriodTo #[datetime]::parseexact($_.PeriodTo,'yyyy-MM-ddThh:mm:ss', $null).ToString('yyyy-MM-dd')
          BillingName = $_.BillingName
          BillingAddress = $_.BillingAddress
          BillingAttentionTo = $_.BillingAttentionTo
          BillingCity = $_.BillingCity
          BillingState = $_.BillingState
          BillingPostalCode = $_.BillingPostalCode
          RemitToName = $_.RemitToName
          RemitToAddress = $_.RemitToAddress
          RemitToAttentionTo = $_.RemitToAttentionTo
          RemitToCity = $_.RemitToCity
          RemitToState = $_.RemitToState
          RemitToPostalCode = $_.RemitToPostalCode
          Lease = $_.Lease
          Schedule = $_.Schedule
          CreatedDate = $_.CreatedDate #[datetime]::parseexact($_.CreatedDate, 'yyyy-MM-ddThh:mm:ss',    $null).ToString('yyyy-MM-dd')
          }
      New-Object psobject -Property $Properties
   } | Export-Excel $outputcsv
  </code></pre>
  
  <p>Just updating because I may not have been clear on what the issue is. In the columns 'DueDate', 'PeriodFrom', 'PeriodTo', and 'CreatedDate', these are all pulled from the REST API. 'DueDate' and 'CreatedDate' seem to be properly populated but 'PeriodFrom' and 'PeriodTo' may or may not have a date.</p>
  
  <p>Currently, without any trickery, the date (if it exists) returns as:</p>
  
  <pre><code>2019-09-05T00:00:00
  </code></pre>
  
  <p>I would like to return an empty field if it does not exist or return the date in the like the following if it does exit:</p>
  
  <pre><code>2019-09-05
  </code></pre>