I'm having an issue with calling `Invoke-SqlCmd` when it contains a second `Invoke-SqlCmd` call:

```
function Get-Foo
{

  $query=`
@"
WITH data AS 
(
  SELECT  1 ID, 'A' NAME
  UNION ALL
  SELECT  2 ID, 'B' NAME
  UNION ALL
  SELECT  3 ID, 'C' NAME
)
SELECT  *
FROM    data
"@

  Invoke-SqlCmd -ServerInstance "SERVER" -Database "DATABASE" -Query $query

}

function Get-Bar
{
  param
  (
    [int]$ParentId
  )

  $query=`
@"
WITH data AS 
(
  SELECT  1 ID, 'A' NAME, 1 PARENT_ID
  UNION ALL
  SELECT  2 ID, 'B' NAME, 1 PARENT_ID
  UNION ALL
  SELECT  3 ID, 'C' NAME, 2 PARENT_ID
)
SELECT  *
FROM    data
WHERE   parent_id = $ParentId
"@

  Invoke-SqlCmd -ServerInstance "SERVER" -Database "DATABASE" -Query $query

}

Get-Foo | ForEach-Object {

  Get-Bar -ParentId $_.ID

}

```

The first iteration of the outer loop works fine, but when it attempts the the second iteration, and exception is generated:

> 
> Invoke-SqlCmd : The WriteObject and WriteError methods cannot be
>  called from outside the overrides of the BeginProcessing,
>  ProcessRecord, and EndProcessing methods, and they can only be called
>  from within the same thread. Validate that the cmdlet makes these
>  calls correctly, or contact Microsoft Customer Support Services. At
>  Untitled-1.ps1:18 char:3
>  + Invoke-SqlCmd -ServerInstance "SERVER" -Database "DATABASE ...
>  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>  + CategoryInfo : InvalidResult: (SERVER:PSObject) [Invoke-Sqlcmd], PSInvalidOperationExceptio n
>  + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
> 
> 
> 

This syntax works, however:

```
$foo = Get-Foo
$foo | ForEach-Object {

  Get-Bar

}

```

I'm guessing that I need to close the first `Invoke-SqlCmd`, but perhaps there is another solution.