简体   繁体   English

在 PowerShell 中更改 function 中变量的声明数据类型

[英]Change a declared data type of a variable inside a function in PowerShell

I have a PowerShell script where I want to declare a variable data type at the beginning, and there is a function that changes this data type on certain conditions.我有一个 PowerShell 脚本,我想在开始时声明一个变量数据类型,并且有一个 function 在某些条件下更改此数据类型。 I can make it work if this is done outside of the function, but I can't change the data type inside the function, even though I use scope modifiers.如果这是在 function 之外完成的,我可以使它工作,但我无法更改 function 内的数据类型,即使我使用 scope 修饰符。

If I put this in script foobar:如果我把它放在脚本 foobar 中:

[string]$foo = "123"
[int]$foo = $foo
$foo.GetType()

And execute the script:并执行脚本:

PS C:\> .\foobar.ps1

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

But if I put this:但如果我把这个:

[string]$foo = "123"
Function bar {
    [int]$script:foo = $foo
    $foo.GetType()
}
bar

And I execute:我执行:

PS C:\> .\bar.ps1

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

The important note here is that the second scenario only happens if you execute the code from a script.这里需要注意的是,第二种情况仅在您从脚本执行代码时才会发生。 The result will be different when executing directly from terminal.直接从终端执行时结果会有所不同。 I want the data type to change to integer on both scenarios.我希望在两种情况下都将数据类型更改为 integer。 Any ideas?有任何想法吗?

Pass in reference variables like below传入参考变量,如下所示

[string]$foo = "123"

Function bar([ref]$foo) {
[int]($foo)  ='123'
    
 ##  Get-Variable -Name foo -Scope global | select fullname
$foo.GetType()
 }

You can specify what that output object would be with [OutputType()]您可以使用[OutputType()]指定 output object 的内容

[string]$foo = "123"
Function bar {
    [OutputType([int])]
    [int]$script:foo = $foo
    $foo.GetType()
}
bar

You can read more about it here outputType你可以在这里阅读更多关于它的输出类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM