Search code examples
sql-serverpowershelldbatools

Select values from Array based on name


I have extracted some details of a SQL instance using:

$SQLInstance1 = Get-DbaInstanceProperty -SqlInstance SQL | Select-Object ComputerName, Name, Value  | Where-Object Name -In ("FullyQualifiedNetName", "Edition", "PhysicalMemory", "Processors", "VersionString", "Collation", "IsClustered", "ResourceLastUpdateDateTime")

What's the best way to assign these values to variables from an Array output like this:

ComputerName Name Value


SQL Edition Enterprise Edition (64-bit) SQL PhysicalMemory 1571485
SQL Processors 40
SQL VersionString 11.0.7493.4
SQL Collation Latin1_General_CI_AS
SQL IsClustered True
SQL ResourceLastUpdateDateTime 24/12/2019 9:58:55 PM
SQL FullyQualifiedNetName PTHSQL13.FMG.local

So I would want to assign $ComputerName = ComputerName, $Edition = Edition etc from above which I can then use to update a SQL table $ComputerName


Solution

  • Okay. First you need to convert the results to a Dictionary, and then create a new object using that dictionary of properties.

    For example:

    $dict = @{ }
    
    (Get-DbaInstanceProperty -SqlInstance localhost | Select-Object ComputerName, Name, Value | Where-Object Name -In ("FullyQualifiedNetName", "Edition", "PhysicalMemory", "Processors", "VersionString", "Collation", "IsClustered", "ResourceLastUpdateDateTime")).GetEnumerator() | % { $dict.Add($_.Name, $_.Value) }
    
    New-Object -TypeName PSObject -Property $dict
    
    $result = New-Object -TypeName PSObject -Property $dict
    
    $result.FullyQualifiedNetName
    
    $result.Processors
    

    The above code should print out both FullyQualifiedNetName value and Processors count.