Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code working a bit differently between Powershell.exe and Powershell ISE - Sort-Object behavior

I've got a bit of code to get hyperlinks from http webpage - find all items matching criteria, then find newest by sorting them and use it's InnerText as source for download. All hyperlinks get assigned a 7-digit number at the end of their name with greater number for newer files.

Code:

$Web = ((Invoke-WebRequest "http://serveraddress/Export/").Links | 
         Where-Object {$_.href -like “xx_yyyyyy_auto_standard*”} | 
           Sort Name –Desc | Select –Last 1).innertext
Start-BitsTransfer -Source http://serveraddress/Export/$Web -Destination C:\autoreports\

Now, when I run above in Powershell.exe (e.g. when launching .ps1 file by right-click and "Run with Powershell") I get the oldest file downloaded. When I run above in Powershell ISE I get newest file. When I changed -Last to -First in Powershell.exe code works as expected.

I can easily change this, but since I'm very new to Powershell - why is there such difference between Powershell ISE and "standard"? Thanks in advance! While this might be rookie question, I did not find - or understand - reason for the difference.

like image 632
user10359907 Avatar asked Mar 17 '26 14:03

user10359907


1 Answers

To complement Jordan's helpful answer, which solves your specific problem:

As stated, Sort-Object quietly accepts nonexistent properties to sort by.

Unfortunately, as of Windows PowerShell v5.1, attempting to sort by a nonexistent property results in seemingly random output order:

WinPS> 1, 2, 3, 4 | Sort-Object -Property Foo
3
4
1
2

Fortunately, this problem has been fixed in PowerShell Core, where the input order is preserved in that case.

like image 109
mklement0 Avatar answered Mar 21 '26 07:03

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!