private/ConvertTo-DataType.ps1
<#
.SYNOPSIS Converts a string to the appropriate data type. .DESCRIPTION The ConvertTo-DataType function takes a string as input and converts it to the appropriate data type. If the string is empty or null, it returns the input string as is. If the string can be converted to an integer or a double, it returns the converted value. If the string can be converted to a datetime object, it returns the datetime object. Otherwise, it returns the input string as a string. .PARAMETER string The string to be converted to a data type. .EXAMPLE ConvertTo-DataType "123" 123 Converts the string "123" to an integer. .NOTES Function : ConvertTo-DataType Author : John Billekens Copyright: Copyright (c) AppVentiX Version : 1.0 #> function ConvertTo-DataType { [cmdletbinding()] Param( [Parameter(ValueFromPipeLine)] [String]$string ) Process { if ([String]::IsNullOrEmpty($string)) { $output = $string } elseif ($string -as [int] -or $string -as [double]) { if ($string -as [int] -eq $string -as [double]) { $output = $string -as [int] } else { $output = $string -as [double] } } elseif ($string -as [datetime]) { $output = $string -as [datetime] } else { $output = [String]$string } Write-Output $output } } |