如何动态设置PowerShell变量的类型?

tko*_*sih 6 powershell

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

以下是我试图转换为使其更安全的功能(即不涉及调用字符串):

Function ParseLine($Type, $VariableName, $Value){
    Invoke-Expression "[$Type] `$$VariableName = $Value"
}
Run Code Online (Sandbox Code Playgroud)

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

我期望看起来像下面的东西,但我找不到参数Type或等价物:

Function ParseLine($Type, $VariableName, $Value){
    New-Variable -Name $VariableName -Value $Value -Type ([type] $Type)
}
Run Code Online (Sandbox Code Playgroud)

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

$ResponseLogFormat = New-InputFormat {
    ParseLine -Type int -VariableName RecordLength
    RepeatedSection -RepeatCount $RecordLength {
        ParseLine string +ComputerName
        ParseLine double +AverageResponse
    }
}

$ResponseLogFormat.Parse( $FilePath )
Run Code Online (Sandbox Code Playgroud)

mjo*_*nor 10

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

Function ParseLine($Type, $VariableName, $Value){
    Set-Variable $VariableName -Scope 1 -Value ($Value -as ($Type -as [type]))
}
Run Code Online (Sandbox Code Playgroud)

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

我不确定你对变量的意图,但如果你想在函数完成后继续它,你需要在父范围内设置它.