PoshCode Logo PowerShell Code Repository

Out-DataTable by Chad Miller 4 years ago (modification of post by Chad Miller view diff)
View followups from Chad Miller, vpodans and Samuel | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2119"></script>download | new post

Creates a DataTable for an object, based on script by Marc van Orsouw

  1. #######################
  2. <#
  3. .SYNOPSIS
  4. Creates a DataTable for an object
  5. .DESCRIPTION
  6. Creates a DataTable based on an objects properties.
  7. .INPUTS
  8. Object
  9.     Any object can be piped to Out-DataTable
  10. .OUTPUTS
  11.    System.Data.DataTable
  12. .EXAMPLE
  13. $dt = Get-Alias | Out-DataTable
  14. This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable
  15. .NOTES
  16. Adapted from script by Marc van Orsouw see link
  17. Version History
  18. v1.0   - Chad Miller - Initial Release
  19. v1.1   - Chad Miller - Fixed Issue with Properties
  20. .LINK
  21. http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
  22. #>
  23. function Out-DataTable
  24. {
  25.     [CmdletBinding()]
  26.     param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
  27.  
  28.     Begin
  29.     {
  30.         $dt = new-object Data.datatable  
  31.         $First = $true
  32.     }
  33.     Process
  34.     {
  35.         foreach ($object in $InputObject)
  36.         {
  37.             $DR = $DT.NewRow()  
  38.             foreach($property in $object.PsObject.get_properties())
  39.             {  
  40.                 if ($first)
  41.                 {  
  42.                     $Col =  new-object Data.DataColumn  
  43.                     $Col.ColumnName = $property.Name.ToString()  
  44.                     $DT.Columns.Add($Col)
  45.                 }  
  46.                 if ($property.IsArray)
  47.                 { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }  
  48.                 else { $DR.Item($property.Name) = $property.value }  
  49.             }  
  50.             $DT.Rows.Add($DR)  
  51.             $First = $false
  52.         }
  53.     }
  54.      
  55.     End
  56.     {
  57.         Write-Output @(,($dt))
  58.     }
  59.  
  60. } #Out-DataTable

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me