如何动态设置 PowerShell 变量的类型? [英] How do I dynamically set the type of PowerShell variables?

查看:37
本文介绍了如何动态设置 PowerShell 变量的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从字符串中获取 System.Type,然后将其应用于变量?

以下是我尝试转换以使其更安全的函数(即不涉及调用字符串):

函数 ParseLine($Type, $VariableName, $Value){调用表达式[$Type] `$$VariableName = $Value"}

我查看了New-VariableSet-Variable,但定义中没有与类型设置相关的参数.

我希望得到如下所示的内容,但我找不到参数 Type 或等效参数:

函数 ParseLine($Type, $VariableName, $Value){新变量 -Name $VariableName -Value $Value -Type ([type] $Type)}

上下文:我正在尝试创建一个简单的解析器定义,如下所示:

$ResponseLogFormat = New-InputFormat {ParseLine -Type int -VariableName RecordLengthRepeatedSection -RepeatCount $RecordLength {ParseLine 字符串 +ComputerNameParseLine double +AverageResponse}}$ResponseLogFormat.Parse( $FilePath )

解决方案

您可以使用 -as 运算符将变量转换为特定类型:

函数 ParseLine($Type, $VariableName, $Value){Set-Variable $VariableName -Scope 1 -Value ($Value -as ($Type -as [type]))}

这将使用 -as$Type 字符串创建一个类型,然后使用它来转换 $Value.

我不确定你对这个变量的意图,但是如果你想在函数完成后持久化它,你需要在父作用域中设置它.

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 )

解决方案

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.

这篇关于如何动态设置 PowerShell 变量的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆