使用 New-Variable 函数创建变量时如何显式声明变量的类型?

4 powershell

如何强制转换myCharNew-Variable -Name myChar -Value "=" -Option ReadOnlytype [char],或者(更一般地)如何指定使用 创建的变量的类型New-Variable

谢谢

编辑(归功于@veefu):

[char]$sampleVariable="A"
$sampleAttributes=(Get-Variable -Name sampleVariable).Attributes[0]
New-Variable -Name myVariable
(Get-Variable -Name myVariable).Attributes.Add($sampleAttributes)
$myVariable="ab" # GENERATES CONVERSION ERROR (WHICH HELPS A LOT)
$myVariable="a"  # DOES NOT GENERATE CONVERSION ERROR (EVERYTHING'S FINE)
Run Code Online (Sandbox Code Playgroud)

编辑(归功于@postanote):

[char]$anyCharacter="A"
# FOLLOWING LINE GENERATES CONVERSION ERROR (GOOD THING)
Set-Variable -Name anyCharacter -Value "ab" -Option ReadOnly
# FOLLOWING LINE DOES NOT GENERATE CONVERSION ERROR (GREAT)
Set-Variable -Name anyCharacter -Value "a" -Option ReadOnly
Run Code Online (Sandbox Code Playgroud)

Bru*_*tte 5

现在在 PowerShell 中这几乎不可能做到,所以我提出了一个问题您应该能够使用 New-Variable 在变量上设置类型转换属性来解决这个问题。