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

标签 powershell

怎么投 myCharNew-Variable -Name myChar -Value "=" -Option ReadOnly输入 [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)

编辑(归功于@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

最佳答案

现在在 PowerShell 中几乎不可能做到这一点,所以我打开了一个问题 You should be able to set the type conversion attribute on a variable with New-Variable来解决这个问题。

关于powershell - 使用 New-Variable 函数创建变量时如何显式声明变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905423/

相关文章:

powershell - Get-ChildItem和不间断空格

powershell - 如何从 PowerShell 中的连接字符串获取数据库名称

powershell - 在远程计算机上使用 PowerShell 调用 Get-Service 时,为什么会出现 "Get-WindowSize"未实现错误?

Powershell 桌面刷新

powershell - 当键是字符串时,从数组中迭代获取值的正确方法是什么?

exception - Powershell导出不起作用

windows-7 - 在 Windows 7 中使用 WMI/powershell 获取屏幕分辨率

powershell - Select 方法返回类似 @{Name= 的字符串

xml - Powershell xml访问 key 对值

powershell - 如何使用 Powershell 从注册表中的值获取数据