Skip to content

Instantly share code, notes, and snippets.

@asheroto
Last active March 16, 2023 13:23
Show Gist options
  • Save asheroto/e589f10e8c31ba4bab3776e27f4e3de3 to your computer and use it in GitHub Desktop.
Save asheroto/e589f10e8c31ba4bab3776e27f4e3de3 to your computer and use it in GitHub Desktop.
Sort/alphabetize a custom PowerShell object by property name such as when using a command line Get-Host.

Sort-Custom

Sort/alphabetize a custom PowerShell object by property name such as when using a command line Get-Host.

Example

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

function Sort-Custom {
	[CmdletBinding()]
	param ( [Parameter (ValueFromPipeline) ]
		$Variable
	)
	begin { }
	process {
		$Variable | fl -property ($Variable | gm | sort name).name
	}
	end { }
}

Installation/Usage

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

Credits for the method used in the function go to John Anson for his StackOver.com answer.

Credits for the function go to asheroto.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment