PoshCode Logo PowerShell Code Repository

Out-DataTable by Chad Miller 4 years ago
View followups from Chad Miller | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2116"></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. .LINK
  20. http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
  21. #>
  22. function Out-DataTable
  23. {
  24.     [CmdletBinding()]
  25.     param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
  26.  
  27.     Begin
  28.     {
  29.         $dt = new-object Data.datatable  
  30.         $First = $true
  31.     }
  32.     Process
  33.     {
  34.         foreach ($object in $InputObject)
  35.         {
  36.             $DR = $DT.NewRow()  
  37.             $object.PsObject.get_properties() | foreach
  38.             {  
  39.                 if ($first)
  40.                 {  
  41.                     $Col =  new-object Data.DataColumn  
  42.                     $Col.ColumnName = $_.Name.ToString()  
  43.                     $DT.Columns.Add($Col)
  44.                 }  
  45.                 if ($_.IsArray)
  46.                 { $DR.Item($_.Name) =$_.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }  
  47.                 else { $DR.Item($_.Name) = $_.value }  
  48.             }  
  49.             $DT.Rows.Add($DR)  
  50.             $First = $false
  51.         }
  52.     }
  53.      
  54.     End
  55.     {
  56.         Write-Output @(,($dt))
  57.     }
  58.  
  59. } #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