Functions/Set-Type.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
filter Set-Type { <# .SYNOPSIS Sets the data type of a property given the property name and the data type. .DESCRIPTION Sets the data type of a property given the property name and the data type. This is needed as cmdlets such as Import-CSV pulls everything in as a string datatype so you can't sort numerically or date wise. .PARAMETER TypeHash A hashtable of property names and their associated datatype .NOTES # inspired by https://mjolinor.wordpress.com/2011/05/01/typecasting-imported-csv-data/ Changes * reworked with begin, process, end blocks * reworked logic to work properly with pwsh and powershell .EXAMPLE $csv = Import-CSV -Path .\test.csv | Set-Type -TypeHash @{ 'LastWriteTime' = 'DateTime'} .LINK about_Properties #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','')] param( [parameter(ValueFromPipeLine)] [psobject[]] $InputObject, [hashtable] $TypeHash ) begin { Write-Verbose -Message "Starting [$($MyInvocation.Mycommand)]" } process { foreach ($curObject in $InputObject) { foreach ($key in $($TypeHash.keys)) { $curObject.$key = $($curObject.$key -as $($TypeHash[$key])) } $curObject } } end { Write-Verbose -Message "Ending [$($MyInvocation.Mycommand)]" } } |