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
}
source
share