Ordering variable in PowerShell

chetan Vishwakarma 146 Reputation points
2021-11-16T10:28:01.047+00:00

Hello Team ,

I have to print variables in Order in PowerShell , Could you please help in that?

For example i have multiple variable with 0 and 1 values , Now i wanted to print all variables with value 1 in first and rest will be print after that (0,1 is the auto generated Values for Variables)

$val = 0
$val1 = 1
$val2 = 0
$val3 = 1
$val4 = 1
$val5=1
$val6=0

Expected :
$VarConcatinate = $val1+" "+$val3+" "+$val3+" "+$val4+" "+$val5+" "+$val+" "+$val2+" "+$val6

All Values with 1 should come first.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,362 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Clément BETACORNE 2,031 Reputation points
    2021-11-16T11:10:41.16+00:00

    Hello,

    If you will always have 6 variables you can try to add them to a collection for example :

    $val = 0
    $val1 = 1
    $val2 = 0
    $val3 = 0
    $val4 = 1
    $val5 = 1
    $val6 = 0
    $colVariables = @($val, $val1,$val2,$val3,$val4,$val5,$val6)

    $colVariables | Sort-Object -Descending


  2. Rich Matheisen 44,776 Reputation points
    2021-11-16T15:55:53.133+00:00

    Does it matter what the variable NAMES are? In other words, do you want all the variable names that begin with "val"?

    Using the example you gave . . .

    If you want only the variables whose name begins with "val", and only their VALUES and not the NAMES of the variables in the output, then this will work:

    Get-Variable -Name val* | 
        Sort-Object Value,Name  -Descending | 
            Select-Object -Expand value
    

    If you want NAME and Value:

    Get-Variable -Name val* | 
        Sort-Object Value,Name  -Descending | 
            ForEach-Object{
                "{0}`t{1}" -f $_.Name, $_.Value
            }
    

    Or this:

    Get-Variable -Name val* | 
        Sort-Object Value,Name  -Descending
    
    0 comments No comments

  3. Limitless Technology 39,351 Reputation points
    2021-12-16T18:21:09.707+00:00

    The Sort-Object cmdlet sorts objects in ascending or descending order based on object property values. If sort properties are not included in a command, PowerShell uses default sort properties of the first input object. If the type of the input object has no default sort properties, PowerShell attempts to compare the objects themselves.

    You can dig deep about this command from here
    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/sort-object?view=powershell-7.2

    ----

    --If the reply is helpful, please Upvote and Accept it as an answer--

    0 comments No comments