PowerShell排序顺序不正确。

4

我想使用PowerShell将C#的"using"语句排序到文件顶部。对于给定的输入文件File.cs,using语句如下:

using System.Reflection;
using System.Configuration;
using System.Runtime.Caching;
using System.Linq;
using System;

我希望输出结果中“using System”作为第一个“using”,但实际上Sort-Object将其排序到底部。我该如何更改以使其排在列表的顶部?

function Update-UsingStatements
{
  param (
    [Parameter(Mandatory=$true)][string]$FilePath
  )

  $fileLines = Get-Content $FilePath
  $contents = $fileLines | Out-String

  $list = New-Object 'System.Collections.Generic.List[string]'
  $contents | Select-String -pattern 'using\s[\w\.]+;' -AllMatches | ForEach-Object {$_.Matches} | ForEach-Object { $list.Add($_.Value) }
  $list = $list | Sort-Object

  for ($i = 0; $i -lt $list.Count; $i++)
  {
    $fileLines[$i] = $list[$i]
  }

  $fileLines | Out-File $FilePath -Encoding utf8
}
2个回答

5
您得到这种排序方式是因为字符串包含尾随的;,在字符表中;(ASCII字符59)在.(ASCII字符46)之后。所以排序顺序是完全正确的,即使不是您预期的顺序。
通过删除排序属性中的尾随分号来解决这个问题:
$list = $list | Sort-Object { $_ -replace ';' }

我有些晚了,但是恭喜你达成了10万声望的成就。请接受来自我这个谦卑之人的最大敬意。你的清晰明了的答案理所应得。 - sodawillow
3
我有同样的想法,但是我打算使用$_.TrimEnd(';')而不是-replace。把它作为一个单独的答案发表似乎太浪费了,所以我只是在你的评论中添加选项。非常准确的答案Ansgar,干得好! - TheMadTechnician
@sodawillow 谢谢。 - Ansgar Wiechers

3

使用Ansgar Wiechers的排序调整作为主要修复,您可以在代码的其余部分中摆脱许多古老的计数扭曲:

function Update-UsingStatements
{
  param (
    [Parameter(Mandatory=$true)][string]$FilePath
  )

  # Separate the 'using' statements from everything else
  $using, $rest = (Get-Content -Path $FilePath).where({$_ -match '^using '}, 'split')

  # sort the 'using' statements, with a tweak to bring 'using system;' to the top
  $using = $using | Sort-Object -Property { $_ -replace ';' }

  # output sorted 'using' statements and rest of file, over the original file
  $using, $rest | Set-Content -Path $FilePath -Encoding UTF8

}

我是一名C#程序员,正在尝试混合编写PowerShell脚本 - 我很欣赏您的改进。更加优雅了!+1给“古老的计数扭曲”。 - Andy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接