I need some help with a async Powershell call that fails with either (1) max recursion depth exceeded or (2) invalid input argument.
The basic setup is as follows...
- Coding and debugging done in VSCode
- Powershell version is 5.1.19041 - desktop edition
- Function to connect to SSAS server
- Recursive function called by first function to convert object to XML
- Create a Powershell session to execute the functions with parameters
- BeginInvoke(), wait for completion, process results
Is there something with the async call that is messing with my code such that the comparison between $NestLevel and $MaxDepth is invalid or that $MaxDepth is set to 0?
I've gone over this a hundred times and I don't see anywhere $MaxDepth is ever set to anything below 1. The "if ( $NestLevel -gt $MaxDepth ) { return }" should terminate recursion but doesn't seem like it is.
Am I missing something?
Code example...
function Test-Recursion {
Param (
[Parameter(Mandatory=$false)]
$InputObject,
[Parameter(Mandatory=$false)]
[ValidateRange(1,100)]
[Int16] $MaxDepth = 2
)
[Int16] $_NestLevel_ += 1
if ( $_NestLevel_ -gt $MaxDepth ) { return }
"<item><nest_level>$($_NestLevel_)</nest_level><max_depth>$($MaxDepth)</max_depth></item>"
& $MyInvocation.MyCommand.ScriptBlock -InputObject $InputObject -MaxDepth $MaxDepth
}
function Get-Info {
Param (
[Parameter(Mandatory=$true)]
[String] $HostName,
[Parameter(Mandatory=$true)]
[ScriptBlock] $ConvertTo
)
$some_collection | `
ForEach-Object {
@(
$_as | ForEach-Object {
& $ConvertTo -InputObject $_ -MaxDepth 3
}
) | Sort-Object
}
}
# this code fails with either...
# - excessive recursion depth
# - invalid $MaxDepth value of 0
try {
$_ps = [powershell]::Create()
$null = $_ps.AddScript(${function:Get-Info})
$null = $_ps.AddParameter('HostName', 'some_server_name')
$null = $_ps.AddParameter('ConvertTo', ${function:Test-Recursion})
$_handle = $_ps.BeginInvoke()
while ( -Not $_handle.IsCompleted ) {
Start-Sleep -Seconds 5
}
$_result = $_ps.EndInvoke($_handle)
$_result
} catch {
$_
} finally {
$_ps.Dispose()
}
# this code works as expected
$items = Get-Info -HostName 'some_server_name' -ConvertTo ${function:Test-Recursion}
$items.table_data
Queueinstead of recursion, see a similar issue here stackoverflow.com/a/71366308/15339544