Why does powershell change my result?

I will build the following CustomObjectin my function

    New-Object -Type PSCustomObject -Property @{
        Computername      = $_
        PowerShellVersion = $result[0]
        dotNetVersion     = $result[1]
        sqlnacli          = $result[2]
        redistributable   = $result[3]
    }

But the conclusion is as follows:

PowerShellVersion Computername redistributable sqlnacli dotNetVersion
----------------- ------------ --------------- -------- -------------
3+ OK             SERVERNAME     NOT OK          NOT OK   NOT OK    

why is PowerShell reordering the order of my object and how can I make it accept the order in which I want it?

+5
source share
2 answers

Hashtables are not sorted by definition. If you have PowerShell v3.0 or later, you can use the attribute [Ordered]for the hash table:

New-Object PSCustomObject -Property ([Ordered] @{
  Computername      = $_
  PowerShellVersion = $result[0]
  dotNetVersion     = $result[1]
  sqlnacli          = $result[2]
  redistributable   = $result[3]
})

In PowerShell v3 +, you can also just use a [PSCustomObject]type like this [PSCustomObject]:

[PSCustomObject] @{
  Computername      = $_
  PowerShellVersion = $result[0]
  dotNetVersion     = $result[1]
  sqlnacli          = $result[2]
  redistributable   = $result[3]
}

If you need compatibility with PowerShell version 2, you can use

New-Object PSObject -Property @{
  Computername      = $_
  PowerShellVersion = $result[0]
  dotNetVersion     = $result[1]
  sqlnacli          = $result[2]
  redistributable   = $result[3]
} | Select-Object Computername,PowerShellVersion,dotNetVersion,sqlnacli,redistributable

, , , Select-Object.

PowerShell v2 - - (, ), Select-Object , :

$obj = $_
"" | Select-Object '
  @{Name = "Computername";      Expression = {$obj}},
  @{Name = "PowerShellVersion"; Expression = {$result[0]}},
  @{Name = "dotNetVersion";     Expression = {$result[1]}},
  @{Name = "sqlnacli";          Expression = {$result[2]}},
  @{Name = "redistributable";   Expression = {$result[3]}}

() , $_ Select-Object , (, $obj = $_ , ).

+8

@wOxxOm @Bill_Stewart, -, , - . - select, :

New-Object -Type PSCustomObject -Property @{
    Computername      = $_
    PowerShellVersion = $result[0]
    dotNetVersion     = $result[1]
    sqlnacli          = $result[2]
    redistributable   = $result[3]
} | Select-Object Computername,PowerShellVersion,dotNetVersion,sqlnacli,redistributable
+3

Source: https://habr.com/ru/post/1670082/


All Articles