Created
August 3, 2021 12:47
-
-
Save SQLvariant/c3587458c03a67bf4eb17009a5fa3b40 to your computer and use it in GitHub Desktop.
v1.1 of Chad Miller's Out-DataTable PowerShell function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
####################### | |
<# | |
.SYNOPSIS | |
Creates a DataTable for an object | |
.DESCRIPTION | |
Creates a DataTable based on an objects properties. | |
.INPUTS | |
Object | |
Any object can be piped to Out-DataTable | |
.OUTPUTS | |
System.Data.DataTable | |
.EXAMPLE | |
$dt = Get-Alias | Out-DataTable | |
This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable | |
.NOTES | |
Adapted from script by Marc van Orsouw see link | |
Version History | |
v1.0 - Chad Miller - Initial Release | |
v1.1 - Chad Miller - Fixed Issue with Properties | |
.LINK | |
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx | |
#> | |
function Out-DataTable | |
{ | |
[CmdletBinding()] | |
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject) | |
Begin | |
{ | |
$dt = new-object Data.datatable | |
$First = $true | |
} | |
Process | |
{ | |
foreach ($object in $InputObject) | |
{ | |
$DR = $DT.NewRow() | |
foreach($property in $object.PsObject.get_properties()) | |
{ | |
if ($first) | |
{ | |
$Col = new-object Data.DataColumn | |
$Col.ColumnName = $property.Name.ToString() | |
$DT.Columns.Add($Col) | |
} | |
if ($property.IsArray) | |
{ $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 } | |
else { $DR.Item($property.Name) = $property.value } | |
} | |
$DT.Rows.Add($DR) | |
$First = $false | |
} | |
} | |
End | |
{ | |
Write-Output @(,($dt)) | |
} | |
} #Out-DataTable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment