Is there a way to use a parent connection/scope, in a lower level script block?

Product: PowerShell Universal
Version: 2.10.2

Hey y’all,

Let’s say I’m running a multi-page dashboard, in the PSU integrated environment, and working with one of the pages. This page will need to make a connection to Jira early on to look up some info. This scenario applies to other connections like PowerCLI, Azure, AzureAD, ExchangeOnline, etc.

Later I have buttons, when clicked will open a modal and that will also have buttons; which need to run commands in Jira (or other connection/session source). Problem is when I get down inside these script blocks and try to run commands, the connection/session is not available down in these scopes. This causes me to have to code connections and lookups, with error handling, in each of the action buttons. This is doable, but seems unnecessary.

In a regular PowerShell script, I wouldn’t have this issue as the sub scope would be able to access the connection/session created in the parent scope.

Is there a way to access the parent connection/session scope, when needing to run commands against the connection/session in these lower level script block scopes?

Thanks,
Rob

I’m interested too. I have the same issues.
For the moment I use $session variables.

It depends a little on how the module you are using works. Each endpoint runs in a new runspace that has been reset for the current execution. This behavior is different than how PowerShell typically runs (single runspace). $Session scoped variables work since they store data outside of the runspace and within a session-based dictionary of values inside the UD host.

Simple variables should persist down to child scopes. For example:

$Variable = 'test'
New-UDDynamic -Content {
    New-UDTypography -Text $Variable
}

The above code could run in 2 different runspaces but we automatically transfer the variable state down to the dynamic runspace.

Some recommendations I would make would be to avoid calling all your platform specific code directly in the dashboard and put them in a module. This way you can avoid having to redefine all the connect code for each component you are using.

For example (psuedo-code), you could define a couple functions in a module to connect and look up jira issues.

function Connect-ToModules {
 # Connect to Jire
}

function Get-JiraIssue {
    if (-not $Connected) {
        Connect-ToModules
    } 

    Get-JireTickets
}

Then in the dashboard, you wouldn’t have to worry about redefining any connection code since it’s just in the module.

New-UDDyanmic -Content {
   New-UDTypography (Get-JiraIssue).Count
}

New-UDDyanmic -Content {
   New-UDTypography (Get-JiraIssue).Count
}

New-UDDyanmic -Content {
   New-UDTypography (Get-JiraIssue).Count
}
1 Like

Thanks @adam! Everything you said makes sense. I’ll go re-watch the training video on modules and get something in place for connections.

1 Like