select distinct items from a column in powershell
PowershellDistinct ValuesPowershell Problem Overview
If I issue following command in PowerShell, I get a lot of rows back.
PS C:\Users\benh> get-command
CommandType Name ModuleName Definition
----------- ---- ---------- ----------
Cmdlet Get-Variable Microsoft.PowerShell.Utility Get-Variable...
Cmdlet Get-WebAppDomain WebAdministration Get-WebAppDomain...
Cmdlet Get-WebApplication WebAdministration Get-WebApplication...
Cmdlet Get-WebAppPoolState WebAdministration Get-WebAppPoolState...
...
Cmdlet Get-WinEvent Microsoft.PowerShell.Diagnostics Get-WinEvent...
Cmdlet Get-WmiObject Microsoft.PowerShell.Management Get-WmiObject...
Cmdlet Get-WSManCredSSP Microsoft.WSMan.Management Get-WSManCredSSP...
Cmdlet Get-WSManInstance Microsoft.WSMan.Management Get-WSManInstance...
Cmdlet Group-Object Microsoft.PowerShell.Utility Group-Object...
Cmdlet Import-Alias Microsoft.PowerShell.Utility Import-Alias...
Cmdlet Import-Clixml Microsoft.PowerShell.Utility Import-Clixml...
Cmdlet Import-Counter Microsoft.PowerShell.Diagnostics Import-Counter...
Cmdlet Import-Csv Microsoft.PowerShell.Utility Import-Csv...
Cmdlet Import-LocalizedData Microsoft.PowerShell.Utility Import-LocalizedData...
Cmdlet Import-Module Microsoft.PowerShell.Core ...
What I want to do is get all the distinct ModuleNames returned by Get-Command. How can I do this with PowerShell?
In pseudo-C#:
PowerShell.Exec("Get-Command").Select(a=> a.ModuleName).Distinct();
Thanks in advance!
Powershell Solutions
Solution 1 - Powershell
Have you tried something like this?
get-command | select ModuleName | sort-object -Property ModuleName -Unique
Solution 2 - Powershell
Even shorter:
get-command | select-object moduleName -unique
Solution 3 - Powershell
Below 2 commands will bring out same result, but the first one will be sorted and a bit expensive in execution time.
The execution time will be taken more into consideration when you have large number of items, For example if you are importing csv
file of 30,000 rows. Then second option will be faster, and once you get unique values sort them if you need because here sorting will be done on a much lesser number of items hence better performance.
get-command | select ModuleName | sort-object -Property ModuleName -Unique
# This will give you the execution time
Measure-Command {get-command | select ModuleName | sort-object -Property ModuleName -Unique}
2.
get-command | select ModuleName -Unique
# This will give you the execution time
Measure-Command {get-command | select ModuleName -Unique}
Solution 4 - Powershell
Another option:
Get-Command | Group-Object ModuleName -NoElement | Select-Object Name