Powershell.exe 和 Powershell ISE 之间的代码工作方式略有不同 - 对象排序行为

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

我有一些代码可以从 http 网页获取超链接 - 找到所有符合条件的项目,然后通过对它们进行排序找到最新的,并使用它的 InnerText 作为下载源。所有超链接都在其名称末尾分配了一个 7 位数字,新文件的数字越大。

代码:

$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\

现在,当我在 Powershell.exe 上面 运行 时(例如,当通过右键单击和 "Run with Powershell" 启动 .ps1 文件时)我下载了最旧的文件。当我在 Powershell ISE 中 运行 以上时,我得到了最新的文件。当我将 Powershell.exe 中的 -Last 更改为 -First 时,代码按预期工作。

我可以很容易地改变它,但由于我是 Powershell 的新手 - 为什么 Powershell ISE 和 "standard" 之间存在如此大的差异?提前致谢!虽然这可能是菜鸟问题,但我没有找到 - 或理解 - 造成差异的原因。

link 对象没有 "Name" 的 属性,因此无法按名称排序。

补充 ,解决您的具体问题:

如前所述,Sort-Object 悄悄地接受不存在的属性 来排序

不幸的是,从 Windows PowerShell v5.1 开始,尝试按不存在的 属性 进行排序会导致看似随机的输出顺序:

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

幸运的是,此问题已在 PowerShell Core 中得到解决,在这种情况下,输入顺序会保留。