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 )
PowerShell Variable ExamplesYou can create a variable by simply assigning it a value. For example, the command $var4 = “variableexample” creates a variable named $var4 and assigns it a string value. The double quotes (” “) indicate that a string value is being assigned to the variable.
To create a dynamic parameter, you will need to use the DynamicParam keyword. Unlike the Param keyword, you enclose the statement list in curly brackets {}. Dynamic parameters are declared after the Param() definition if used in a cmdlet.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
Following are the different types of variables in the Windows PowerShell: User-Created Variables. Automatic Variables. Preference Variables.
You can cast variables to a specific type using the -as
operator:
Function ParseLine($Type, $VariableName, $Value){
Set-Variable $VariableName -Scope 1 -Value ($Value -as ($Type -as [type]))
}
That will use -as
to create a type from the $Type
string, and then use that to cast $Value
.
I am not sure of your intent with the variable, but if you want to persist it after the function is finished, you need to set it in the parent scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With