Search code examples
powershellpowershell-4.0

Call Rest API inside powershell function


I have called Rest API using powershell function but i need to get date entry from all objects like english-and-wales, scotland , northern ireland. using this $list.'england-and-wales'.events.date i will get only england-and-wales details but remaining scotland, northern ireland date i am unable to fetch

function Get-Holiday {
  Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json

}
$list = Get-Holiday
$list | ConvertTo-Json -Depth 3
$list.'england-and-wales'.events.date

I need to get date entry from all england-and-wales, scotland, northern ireland. can you please provide solution for that

Example image


Solution

  • If you want to combine the dates from all three data sets, you could do something like this:

    # define divisions
    $divisions = 'england-and-wales', 'scotland', 'northern-ireland'
    
    # fetch data 
    $list = Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json
    
    # enumerate dates for all divisions, remove duplicates and assign to a variable
    $allPossibleHolidayDates = $divisions |%{ $list.$_.events.date} |Sort -Unique
    

    At which point you can determine whether a certain date is a holiday by:

    # Get a string representing todays date formatted like "2020-11-18"
    $todaysDate = Get-Date -Format 'yyyy-MM-dd'
    
    # this will now return $true if today is a holiday in any of the divisions
    $allPossibleHolidayDates -contains $todaysDate