locked
Powershell Foreach question not working as expected RRS feed

  • Question

  • I have the following block of code:

    Foreach ($Entry in $data) {
    if($Entry.Title -match "^Devblog") {
    [datetime]$servertime = $Entry.updated
    Write-Output ($Entry.updated)

    }
    }

    The output is this:

    2017-11-03T13:53:20Z
    2017-11-02T19:19:18Z
    2017-10-26T13:06:36Z
    2017-10-19T20:18:06Z
    2017-10-12T17:59:51Z
    2017-10-05T08:32:55Z
    2017-09-28T21:13:02Z
    2017-09-21T08:14:34Z
    2017-09-14T21:50:05Z
    2017-09-07T00:55:09Z

    I am only interested in the value of the very first (latest) entry at the top. Instead, I keep getting the last entry (9/7/2017).  I tried using $Entry.updated[0] but that returns "2" which is the very first character of the last entry. I'm sure this is something obvious so any help is appreciated. 

    Tuesday, November 7, 2017 9:20 PM

Answers

  • The following get you the last filtered entry.

    $uri = 'https://rust.facepunch.com/rss/blog'
    $data = Invoke-RestMethod $uri
    $data.Where({$_.Title -match 'devblog'})[-1]
    


    \_(ツ)_/

    • Marked as answer by Guardian911 Wednesday, November 8, 2017 4:59 AM
    Wednesday, November 8, 2017 4:25 AM

All replies

  • The last entry in an array is -1.

    $data[-1]

    This is  the last entry.


    \_(ツ)_/

    Tuesday, November 7, 2017 9:44 PM
  • Yep, understood. But when I use that, it shows me a value of 'Z' which is the last letter of the entry. That's what's confusing me.

    $Entry.Updated[0] should be the first entry (2017-11-03T13:53:20Z) but instead, it's the first character!

    Wednesday, November 8, 2017 3:29 AM
  • No.  Do not use a loop.  Just get the last element of the data array assuming that you really have an array.


    \_(ツ)_/

    Wednesday, November 8, 2017 3:32 AM
  • The reason I used a loop was because I had to filter out date entries other than the Devblog.

    $uri = 'https://rust.facepunch.com/rss/blog'
    $data = Invoke-RestMethod $uri
    #$data | Select Title,updated

    Foreach ($Entry in $data) {
    if($Entry.Title -match "^Devblog") {
    [datetime]$servertime = $Entry.updated
    Write-Output ($Entry.updated)
    Break

    $data.updated[0] shows the date of the first entry as expected but I also thought enumerating it through a Foreach loop would do the same.

    Wednesday, November 8, 2017 4:18 AM
  • You asked for the last entry and this is how to get the last entry.

    $uri = 'https://rust.facepunch.com/rss/blog'
    $data = Invoke-RestMethod $uri
    $data[-1]
    


    \_(ツ)_/

    Wednesday, November 8, 2017 4:23 AM
  • The following get you the last filtered entry.

    $uri = 'https://rust.facepunch.com/rss/blog'
    $data = Invoke-RestMethod $uri
    $data.Where({$_.Title -match 'devblog'})[-1]
    


    \_(ツ)_/

    • Marked as answer by Guardian911 Wednesday, November 8, 2017 4:59 AM
    Wednesday, November 8, 2017 4:25 AM