Sort/alphabetize a custom PowerShell object by property name such as when using a command line Get-Host
.
Before:
PS C:\> Get-Host
Name : ConsoleHost
Version : 7.3.0
InstanceId :
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
After:
PS C:\> Get-Host | Sort-Custom
CurrentCulture : en-US
CurrentUICulture : en-US
DebuggerEnabled : True
InstanceId :
IsRunspacePushed : False
Name : ConsoleHost
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
Runspace : System.Management.Automation.Runspaces.LocalRunspace
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
Version : 7.3.0
function Sort-Custom {
[CmdletBinding()]
param ( [Parameter (ValueFromPipeline) ]
$Variable
)
begin { }
process {
$Variable | fl -property ($Variable | gm | sort name).name
}
end { }
}
To set this up so you can use it permanently, copy the function into your PowerShell profile. To open your profile, open PowerShell and type notepad $profile
or if you have Visual Studio code then typecode $profile
. Once saved, close and open PowerShell again.
Usage: Pipe a custom object to Sort-Custom
.
Example: Get-Host | Sort-Custom
Credits for the method used in the function go to John Anson for his StackOver.com answer.
Credits for the function go to asheroto.