PowerShell 3.0+全局变量继承机制更改
- 在PowerShell 2.0 中,一个本地变量会继承一个同名的全局变量,在本地变量第一次更改时,会基于旧的值新建一个变量。
- 在PowerShell 3.0,4.0中,一个本地变量会继承一个同名的全局变量,在本地变量第一次更改时,会忽略旧的值,新建一个变量。
此更改,暂无官方文档。我们通过一段脚本来详细说明:MosserTest.ps1
$Global:mylist = @(1,2) [object] ::ReferenceEquals( $Global:mylist , $mylist ) #First Op_Addition $mylist += ( New-Object object) "After First Op_Addition, variable mylist's type is " + $mylist .gettype().fullName [object] ::ReferenceEquals( $Global:mylist , $mylist ) #Second Op_Addition $mylist += ( New-Object object) ' $mylist .Count={0} ' -f $mylist.count ' $Global:mylist .Count={0}' -f $Global:mylist .count |
在PowerShell 2.0 (测试机器:Windows Server 2008 R2)中:
PS> .\mossertest.ps1 True After First Op_Addition, variable mylist's type is System.Object[] False $mylist.Count=4 $Global:mylist.Count=2
在PowerShell 3.0+ (测试机器:Windows 8 Client 和 windows 8.1)中:
PS> .\mossertest.ps1
True
After First Op_Addition, variable mylist's type is System.Object
False
Method invocation failed because [System.Object] does not contain a method named 'op_Addition'.
At C:\Users\asttest\mossertest.ps1:11 char:1
+ $mylist += (New-Object object)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
$mylist.Count=1
$Global:mylist.Count=2
在PowerShell 3.0和4.0中,包含上述逻辑的一些老的脚本可能会运行错误(像Dell的SCOM管理包Dell.ChassisModularServer.Correlation.mp):
Method invocation failed because [System.Object] does not contain a method named ‘op_Addition’.
下面给出三个解决方案可以规避种问题:
- 和运行脚本的控制台共享作用域:
PS> . .\MosserTest.ps1 - 使用全局变量标识符:
$Global:mylist += (New-Object object) - 显式的给本地变量赋值:
$mylist=$Global:mylist
$mylist += (New-Object object)