$MyInvocation.Statement
Property 已在 PowerShell v7.4.0-preview.2 (PR #19027
) 中添加,代表“调用语句的全文”:
function Get-Statement {
param($MyParam)
$MyInvocation.Statement
}
Get-Statement @(
1
2
3)
输出:
Get-Statement @(
1
2
3)
是否可以在 Windows PowerShell 5.1 中获得相同的值?
$MyInvocation.Statement
是从 .ScriptPosition.Text
属性(InvocationInfo.cs#L274-L284
)检索的,该属性在以前的版本(包括 5.1)中已可用,但不公开:
/// <summary>
/// The full text of the invocation statement, may span multiple lines.
/// </summary>
/// <value>Statement that was entered to invoke this command.</value>
public string Statement
{
get
{
return ScriptPosition.Text;
}
}
对于 Windows PowerShell 5.1,我们可以使用反射来获取其值,我们甚至可以通过
Update-TypeData
添加脚本属性到 $MyInvocation
:
$updateTypeDataSplat = @{
MemberType = 'ScriptProperty'
TypeName = 'System.Management.Automation.InvocationInfo'
MemberName = 'Statement'
}
Update-TypeData @updateTypeDataSplat -Value {
if (-not $script:_scriptPosition) {
# cache the PropertyInfo
$script:_scriptPosition = [System.Management.Automation.InvocationInfo].
GetProperty('ScriptPosition', [System.Reflection.BindingFlags] 'Instance, NonPublic')
}
$script:_scriptPosition.GetValue($this).Text
}
现在该属性可用于该会话上的任何函数:
function Get-Statement {
param($Parameter)
$MyInvocation.Statement
}
Get-Statement @(
1
2
3)