Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 获取Powershell中调用函数的名称_Function_Powershell_Invoke - Fatal编程技术网

Function 获取Powershell中调用函数的名称

Function 获取Powershell中调用函数的名称,function,powershell,invoke,Function,Powershell,Invoke,我有以下代码: function foo () { $sb = (Get-Command bar -CommandType Function).ScriptBlock Invoke-Command -ScriptBlock $sb } function bar () { demo } function demo () { Write-Host $((Get-PSCallStack)[0].Command) Write-Host $((Get-PSCal

我有以下代码:

function foo () {
    $sb = (Get-Command bar -CommandType Function).ScriptBlock
    Invoke-Command -ScriptBlock $sb
}

function bar () {
    demo
}

function demo () {
    Write-Host $((Get-PSCallStack)[0].Command)
    Write-Host $((Get-PSCallStack)[1].Command)
}

foo
其结果是:

foo
demo
我想得到的是:

bar
demo
问题似乎在于,在函数foo中,我使用Invoke命令cmdlet调用函数栏,powershell将其视为demo的调用函数。据我所知,功能条是在调用demo,而不是foo

我无法理解为什么powershell会以这种方式运行,以及如何让powershell返回给我函数名“bar”。 甚至我想“愚弄”powershell的想法都是这样的:

function bar () {
    $sb = (Get-Command demo -CommandType Function).ScriptBlock
    Invoke-Command -ScriptBlock $sb
}
没有导致任何关于“酒吧”的成功。
我现在正拼命地呼唤你的帮助。

在问题评论中,听起来原来的问题是通过简化方法解决的。但我想我无意中找到了这个问题的答案。我在演示代码中将
.Command
更改为
.FunctionName

function foo () {
    $sb = (Get-Command bar -CommandType Function).ScriptBlock
    Invoke-Command -ScriptBlock $sb
}

function bar () {
    demo
}

function demo () {
    Write-Host $((Get-PSCallStack)[0].FunctionName)
    Write-Host $((Get-PSCallStack)[1].FunctionName)
}

foo
现在,输出显示所需的
bar
(而不是
foo
):

demo
bar

如果您希望在调用堆栈中实际使用
,那么为什么要将定义推入scriptblock而不仅仅是调用它呢?e、 g.
函数foo{bar}
精确。您从未调用过
bar
。您调用了保存在
$sb
中的脚本块(取自
bar
),这正是我没有看到的问题!非常感谢您的回答-非常感谢。