How can I cast myChar
in New-Variable -Name myChar -Value "=" -Option ReadOnly
to type [char]
, or (more generally) how can I specify type of a variable created with New-Variable
?
Thanks
EDIT (credit goes to @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)
EDIT (credit goes to @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
This is pretty much impossible to do now in PowerShell so I've opened an issue You should be able to set the type conversion attribute on a variable with New-Variable to address this.