PowerShell Order Sort Incorrect

So, I'm trying to use PowerShell to sort the C # "using" statements at the top of the file. For this input file File.cs, the usage statements are as follows:

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

I expect the output to have “use the system” as the first “use”, but actually the Sort-Object sorts it from the bottom. How can I change this to sort at the top of the list?

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
}
+4
source share
2 answers

, ;, ; ( ASCII 59) . ( ASCII 46). , , , .

, , :

$list = $list | Sort-Object { $_ -replace ';' }
+5

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

}
+3

Source: https://habr.com/ru/post/1676957/


All Articles