借助 PowerShell,可通过将赋值括在括号 () 内,在表达式中使用赋值。 PowerShell 会传递分配的值。 例如:
# In an `if` conditional
if ($foo = Get-Item $PROFILE) { "$foo exists" }
# Property access
($profileFile = Get-Item $PROFILE).LastWriteTime
# You can even *assign* to such expressions.
($profileFile = Get-Item $PROFILE).LastWriteTime = Get-Date
注意
虽然可使用此语法,但不建议使用它。 在某些情况下,这不起作用,并且代码作者的意图会使其他代码审阅者感到困惑。
限制
赋值大小写并不总是起作用。 如果不起作用,则放弃赋值。 如果创建可变值类型的实例,并尝试将实例保存在变量中且修改其在同一表达式中的某一个属性,则会放弃属性赋值。
# create mutable value type
PS> Add-Type 'public struct Foo { public int x; }'
# Create an instance, store it in a variable, and try to modify its property.
# This assignment is effectively IGNORED.
PS> ($var = [Foo]::new()).x = 1
PS> $var.x
0
区别是你无法返回对值的引用。 本质上,($var = [Foo]::new()) 等效于 $($var = [Foo]::new(); $var)。 不再对变量执行成员访问,而是对变量的输出(即副本)执行成员访问。
解决方法是先创建实例并将其保存在变量中,然后通过变量赋值给该属性:
# create mutable value type
PS> Add-Type 'public struct Foo { public int x; }'
# Create an instance and store it in a variable first
# and then modify its property via the variable.
PS> $var = [Foo]::new()
PS> $var.x = 1
PS> $var.x
1