0

What I am trying to do is returning a table from a function (ListBuilds) that retrieves it from a database. Then places rows from that table into a ListBox so that a row can be selected. The problem is that I cannot access the data in the table. The code in ListBuilds

$table = Invoke-Sqlcmd -ServerInstance $databaseServer -Database $databaseName -Query $sql      

Return $table

The code calling this places the table into an array, which I have a couple of write-hosts added to try and debug.

    $listTable = @(ListBuilds | Format-Table | Out-String)
    write-host "AA $listTable"
    write-host "aa $listtable[0].ScriptName"

The output from the writes are

AA 

ScriptName  ScriptVerNum ScriptLocation                     
----------  ------------ --------------                     

AAAA                   1 C:\win 10 Build tool\TestScript.ps1

BBBB                   1 C:\win 10 Build tool\TestScript.ps1

Test Script            1 C:\win 10 Build tool\TestScript.ps1

aa 

ScriptName  ScriptVerNum ScriptLocation                     
----------  ------------ --------------                     

AAAA                   1 C:\win 10 Build tool\TestScript.ps1

BBBB                   1 C:\win 10 Build tool\TestScript.ps1

Test Script            1 C:\win 10 Build tool\TestScript.ps1

[0].ScriptName 

I was expecting $listTable[0].ScriptName to return just AAAA.

How do I access the contents of the table returned from the function?

  • 1
    you are using Format-Table ... and that DESTROYS your objects, and wraps the remnants in formatting code. [grin] use Select-Object instead if you want to use the objects instead of "stuff" intended for final display on screen OR final output to a plain text file. – Lee_Dailey Mar 26 at 12:50
  • I could not get Select-Object to work but $listTable[0].ScriptName now does and thank you I now have a better understand of how powershell passes data around. – martin Mar 27 at 8:41
  • i'm glad that you got it working ... but PLEASE never, ever, ever use the Format-* cmdlets for anything other than FINAL output to the screen or FINAL output to a plain text file. you get broken objects wrapped in formatting code, not the actual objects. take a look at the returned 4th item in this >>> (Get-ChildItem -Path $env:TEMP -File | Format-Table)[3] <<< note the red error text mentions "Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData". [grin] – Lee_Dailey 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.