在PowerShell中,您可以通过在声明前添加类型名称来强制实施局部变量的类型:
[string]$MyString = 'hello'
或者您可以使用new-variable命令
创建全局变量New-Variable -Name MyGlobalOption -Scope Global -Value [MyEnum]'Option1'
内置全局变量可以强制执行其类型:
# This fails due to invalid cast to [ActionPreference]
$ErrorActionPreference = Get-Date
但是自定义的全局变量不会:
# Works just fine. And now $MyGlobalOption is invalid:
$MyGlobalOption = Get-Date
如何强制执行全局变量的类型?
答案 0 :(得分:4)
尝试这样声明:
[MyEnum]$global:MyGlobalOption = 'Option1'
如果我这样做:
> Set-StrictMode -Off
> [int]$global:MyGlobalOption = 1
> $MyGlobalOption = get-date
Impossibile convertire il valore "20/09/2013 18:00:18" nel tipo "System.Int32". Errore: "Cast da 'DateTime' a 'Int32'
non valido."
In riga:1 car:1
+ $MyGlobalOption = get-date
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
我收到了一个错误。我无法复制你的问题。