感谢 PowerShell 表达式模式,PowerShell 有一些很好的方法来反序列化对象,例如:
Invoke-Expression
cmdlet _Invoke-Command
cmdlet _- 呼叫操作员
&
- 点源PowerShell 脚本文件
我的一般期望是,给定表达式的结果应该与在该表达式的同一序列化版本上使用上面列出的反序列化命令之一相同(有关背景,请参阅“在 PowerShell 中保存哈希表”中的ConvertTo-Expression答案对象表示法(PSON)的问题)。
换句话说:
<Expression> <=> Invoke-Command {<Expression>} <=> &([ScriptBlock]::Create('<Expression>'))
<Expression> <=> Invoke-Expression '<Expression>'
例子:
Get-ChildItem <=> &{Get-ChildItem}
Get-ChildItem <=> Invoke-Command {Get-ChildItem}
Get-ChildItem <=> Invoke-Expression 'Get-ChildItem'
1, 2, 3 <=> &{1, 2, 3}
1, 2, 3 <=> Invoke-Command {1, 2, 3}
1, 2, 3 <=> Invoke-Expression '1, 2, 3'
这确实主要适用于每个表达式,但由于 PowerShell 默认展开(枚举)输出这一事实,在表达式包含具有单个项目的数组的情况下,此定义会有所不同:
,1 <≠> Invoke-Command {,1}
,1 <≠> Invoke-Expression ',1'
,"Test" <≠> Invoke-Command {,"Test"}
,"Test" <≠> Invoke-Expression ',"Test"'
@("Test") <≠> Invoke-Command {@("Test")}
@("Test") <≠> Invoke-Expression '@("Test")'
,@("Test") <≠> Invoke-Command {,@("Test")}
,@("Test") <≠> Invoke-Expression ',@("Test")'
有没有办法防止表达式在被调用(反序列化)时展开?
我正在考虑在PowerShell GitHub 上-NoEnumerate
请求一个参数(类似于 Write-Output
cmdlet),但这仍然会给不支持参数的呼叫操作员和点源留下问题/问题......Invoke-Expression