关于如何在不展开 Get-PSCallStack 的情况下传递 Get-PSCallStack 的任何想法。它似乎是一个 system.object[] 但从我在网上阅读的内容来看,它们在通过和“展开”时不会保持完整。我尝试在前面放置一个逗号以防止它,但这不起作用。

function Pass-Callstack ([System.Object]$arg0) {
Write-Host 'Start Pass-Callstack'
$psCallStack = $arg0
$psCallStackType = $psCallStack.GetType()
$psCallStackLength = $psCallStack.Length
$psCallStackCommand0 = $psCallStack[0].command
$psCallStackCommand1 = $psCallStack[1].command
Write-Host $psCallStackType
Write-Host $psCallStackLength
Write-Host $psCallStackCommand0
Write-Host $psCallStackCommand1
$arg0 | gm
}

function Describe-Callstack {
Write-Host 'Start Describe-Callstack'
$psCallStack = (Get-PSCallStack)
$psCallStackType = $psCallStack.GetType()
$psCallStackLength = $psCallStack.Length
$psCallStackCommand0 = $psCallStack[0].command
$psCallStackCommand1 = $psCallStack[1].command
Write-Host $psCallStackType
Write-Host $psCallStackLength
Write-Host $psCallStackCommand0
Write-Host $psCallStackCommand1
$psCallStack | gm
}
Describe-Callstack
Pass-Callstack (,$psCallStack)

最佳答案

当你将一个参数传递给一个函数而不用管道传递它时,不会展开集合,例如

function ArgShape($p)
{
    $p.GetType().Fullname
    $p.Rank
    $p.Length
    $p[0].GetType().Fullname
}

ArgShape (Get-PSCallstack)

System.Object[]
1
2
System.Management.Automation.CallStackFrame

此外,如果您希望参数数组传递给 Pass-Callstack,您可以像这样指定:
function Pass-Callstack([object[]]$array)

注意使用“系统”。命名空间前缀是可选的。如果 PowerShell 找不到类型,它将在前面加上。此外,将参数指定为 [object] 本质上是无操作的,因为这是默认类型。即 [object]$arg0$arg0 相同。

您还将 $null 传入 Pass-Callstack (尽管包装在单个元素数组中)。变量 $psCallStack 是函数的私有(private)变量,在函数外部不可见,除非你在它前面加上了像 $script:psCallStack 这样的修饰符。一般来说,我不推荐这种方法。您应该像这样从 Describe-Callstack 输出 $pscallstack :
function Describe-Callstack {
Write-Host 'Start Describe-Callstack'
$psCallStack = (Get-PSCallStack)
$psCallStackType = $psCallStack.GetType()
$psCallStackLength = $psCallStack.Length
$psCallStackCommand0 = $psCallStack[0].command
$psCallStackCommand1 = $psCallStack[1].command
Write-Host $psCallStackType
Write-Host $psCallStackLength
Write-Host $psCallStackCommand0
Write-Host $psCallStackCommand1
$psCallStack
}

然后将函数调用的输出分配给一个变量:
$cs = Describe-Callstack

并将其传递到 Pass-Callstack 例如:
Pass-Callstack $cs

关于powershell 通过 system.object[] 无需展开,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3701831/

10-12 17:46