Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically set the type of PowerShell variables?

Tags:

powershell

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 )
like image 302
tkokasih Avatar asked Apr 13 '14 11:04

tkokasih


People also ask

How do you specify variable type in PowerShell?

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.

How do you pass dynamic values in PowerShell?

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.

What is $_ called in PowerShell?

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.

What are the three types of variable in PowerShell?

Following are the different types of variables in the Windows PowerShell: User-Created Variables. Automatic Variables. Preference Variables.


1 Answers

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.

like image 112
mjolinor Avatar answered Sep 30 '22 15:09

mjolinor