Need some scoping help

Here is my scenario.

I have a main script we will call “Main.PS1”
This script loads a module we will call “Functions.PSM1”

Main.PS1 calls a function in Functions.PSM1 called “function get-stuff()”

The Get-Stuff function then calls a third party powershell scirpt and provides parameters through a hash table. Here is the sanitized relevent code:

$ExternalScript = 'C:\Path\To\ExternalScript.ps1'
$PSExe = (Get-Process -Id $pid).Path

$ScriptArgs = @{
   'Arg1'    = "Console"
   'Arg2'    = $Stuff
   'Arg3'    = 0
   'Arg4'    = 'YadaYada'
   'Arg5'    = $MoreStuff
 }

I then call the script as follows:

$objExternalStuff = & $PSExe -Command $ExternaScript @ScriptArgs

This all works just fine, no errors and $ExternalScript runs fine with the arguments provided and generates the expected external output. However, $ExternalScript ALSO returns a dictionary object that I can use/parse in function Get-STuff(), however $objExternalStuff does not contain any useful data. I have NO control over $ExternalScript. If I create a simple Script.PS1 with the relevant code, all is well with both the external output and dictionary object returned from $ExternalScript so somehow my scoping is messed up which leads me to believe there is a correct way to do this. I have asked AI and nothing it provided worked.

If i do a simple test:
if($objExternalStuff -is [System.Object]) {Write-Host "I am an object"}
It reports that it is indeed an object. But when I try to parse the keys in the dictionary object, I get nothing.

Any help is appreciated. I hope I have explained this with enough detail.

Since you say you “have no control” over the external script. You could try to see if you can make the output of that script “the dictionary” go to a CSV file, and then write more code to process those items using the csv. If that works and Export-Csv actually created rows and tables of data, then there may be ways you could manipulate the data without the CSV step. However, since we can’t see the actual code, it would be dificult for us to reproduce the issue and truely help you.

If it returns it fine, why is it not in $objExternalStuff? I will point out that executing with & runs in a child scope where invoking with . will pull variables into the caller scope. Perhaps that can help you get what you need?

1 Like

I totally understand. Some suggestions from AI were along the same lines as your suggestion, but using JSON versus CSV. I think since my call to the external script is nested in my module, I just don’t understand the scope.

Doug, I will try your suggestion. Thanks to both of you for the help.