Is it possible to get a System.Type from a string and then apply it to a variable?
The following is the function that I tried to convert to make it safer (i.e. not involve invoking a string):
Function ParseLine($Type, $VariableName, $Value){
Invoke-Expression "[$Type] `$$VariableName = $Value"
}
I looked at New-Variable
and Set-Variable
, but there is no type-setting-related parameter in the definition.
I expected something that looks like below, but I couldn't find the parameter Type
or equivalent:
Function ParseLine($Type, $VariableName, $Value){
New-Variable -Name $VariableName -Value $Value -Type ([type] $Type)
}
Context: I am experimenting to create a simple parser definition that looks like:
$ResponseLogFormat = New-InputFormat {
ParseLine -Type int -VariableName RecordLength
RepeatedSection -RepeatCount $RecordLength {
ParseLine string +ComputerName
ParseLine double +AverageResponse
}
}
$ResponseLogFormat.Parse( $FilePath )
ParseLine [Convert]::ToDouble +ComputerName
. This would allow your function to support parsing custom types as well, by passing in a scriptblock which returns the new property value. You could support some default converters as well, which it could lookup based on a name, if you want to. Let me know if you want me to write an answer with a sample.ParseLine {[Convert]::ToDouble} +ComputerName
? As for now, I am using function definition likeParseLine($Type,$VariableName,$ParseScript)
with 'anytype' mapped to * so that I can do the following for custom object:ParseLine * Response {New-CustomObject $CurrentLine}
. But it would be interesting to see the converter approach instead :)