poshbotio / PoshBot

Powershell-based bot framework
MIT License
536 stars 108 forks source link

is it possible to use script scope vairables? #188

Closed Riiskyy closed 4 years ago

Riiskyy commented 4 years ago

Query

Is it possible to declare a script variable in the .psm1 file and have different functions read/write to it? I ask because I am declaring on like this:

$VarParams = @{
    'Name'        = 'Results'
    'Value'       = @()
    'Description' = 'The search results'
    'Scope'       = 'Script'
    'Force'       = $True
}
Set-Variable @VarParams

One of my functions writes to this variable and returns the results, which works perfectly. However my second function that looks to this variable and reads the data keeps returning blank results.

When I test this locally in debugging mode it works without any issues. I can see the data being stored in the variable and when calling the second function the data is loaded in to the correct variables.

Context

One function writes to the variable with this code:

$ID = 0
        foreach ($file in $Search) {
            $Script:Results += [PSCustomObject]@{
                ID           = $ID
                Name         = $file.title
                DateAddedUTC = $file.pubDate.Substring(5, 11)
                SizeGB       = [math]::Round($file.size / 1GB, 2)
                DownloadUrl  = $file.link
            }
            $ID++
        }

And then my other function reads data from the variable using this: $Target = ($script:Results | Where-Object { $_.ID -eq $ID })

However when running the commands in Slack I get the following error:

Cannot validate argument on parameter 'Uri'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

Your Environment

devblackops commented 4 years ago

When PoshBot executes a command from your module, it does so in a new PowerShell job and that job is terminated when the command completes. If the command sets a script scope variable, that will only persist for the life of the job. Subsequent commands that PoshBot runs are executed in entirely new jobs and will not have access to that variable value.

If you need to have persist data between PoshBot commands, you can get/set/delete values using Get-PoshBotStatefulData, Set-PoshBotStatefulData, and Remove-PoshBotStatefulData.

Riiskyy commented 4 years ago

Ah that explains a lot. Thank you!